Pass ParserContext down to lengths

To make it possible to check the rule type when parsing lengths, we need to pass
the `ParserContext` down through many layers to the place where length units are
parsed.

This change leaves it unused, so it's only to prepare for the next change.

MozReview-Commit-ID: 70YwtcCxnWw
This commit is contained in:
J. Ryan Stinnett 2017-04-11 16:00:37 +08:00
parent 1ae1d370f2
commit 1a31b87c22
31 changed files with 304 additions and 251 deletions

View file

@ -16,6 +16,7 @@ use dom::window::Window;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use std::sync::Arc; use std::sync::Arc;
use style::media_queries::parse_media_query_list; use style::media_queries::parse_media_query_list;
use style::parser::ParserContext;
use style::shared_lock::{Locked, ToCssWithGuard}; use style::shared_lock::{Locked, ToCssWithGuard};
use style::stylesheets::{CssRuleType, MediaRule}; use style::stylesheets::{CssRuleType, MediaRule};
use style_traits::ToCss; use style_traits::ToCss;
@ -68,10 +69,11 @@ impl CSSMediaRule {
/// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface /// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
pub fn set_condition_text(&self, text: DOMString) { pub fn set_condition_text(&self, text: DOMString) {
let mut input = Parser::new(&text); let mut input = Parser::new(&text);
let win = self.global().as_window(); let global = self.global();
let url = win.Document().url(); let win = global.as_window();
let url = win.get_url();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media)); let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media));
let new_medialist = parse_media_query_list(&mut input); let new_medialist = parse_media_query_list(&context, &mut input);
let mut guard = self.cssconditionrule.shared_lock().write(); let mut guard = self.cssconditionrule.shared_lock().write();
// Clone an Arc because we cant borrow `guard` twice at the same time. // Clone an Arc because we cant borrow `guard` twice at the same time.

View file

@ -32,8 +32,9 @@ use std::default::Default;
use std::sync::Arc; use std::sync::Arc;
use style::attr::AttrValue; use style::attr::AttrValue;
use style::media_queries::parse_media_query_list; use style::media_queries::parse_media_query_list;
use style::parser::ParserContext as CssParserContext;
use style::str::HTML_SPACE_CHARACTERS; use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::Stylesheet; use style::stylesheets::{CssRuleType, Stylesheet};
use stylesheet_loader::{StylesheetLoader, StylesheetContextSource, StylesheetOwner}; use stylesheet_loader::{StylesheetLoader, StylesheetContextSource, StylesheetOwner};
unsafe_no_jsmanaged_fields!(Stylesheet); unsafe_no_jsmanaged_fields!(Stylesheet);
@ -255,7 +256,7 @@ impl HTMLLinkElement {
} }
// Step 2. // Step 2.
let url = match document.base_url().join(href) { let link_url = match document.base_url().join(href) {
Ok(url) => url, Ok(url) => url,
Err(e) => { Err(e) => {
debug!("Parsing url {} failed: {}", href, e); debug!("Parsing url {} failed: {}", href, e);
@ -276,7 +277,10 @@ impl HTMLLinkElement {
}; };
let mut css_parser = CssParser::new(&mq_str); let mut css_parser = CssParser::new(&mq_str);
let media = parse_media_query_list(&mut css_parser); let win = document.window();
let doc_url = document.url();
let context = CssParserContext::new_for_cssom(&doc_url, win.css_error_reporter(), Some(CssRuleType::Media));
let media = parse_media_query_list(&context, &mut css_parser);
let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity")); let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity"));
let integrity_val = im_attribute.r().map(|a| a.value()); let integrity_val = im_attribute.r().map(|a| a.value());
@ -292,7 +296,7 @@ impl HTMLLinkElement {
let loader = StylesheetLoader::for_element(self.upcast()); let loader = StylesheetLoader::for_element(self.upcast());
loader.load(StylesheetContextSource::LinkElement { loader.load(StylesheetContextSource::LinkElement {
media: Some(media), media: Some(media),
}, url, cors_setting, integrity_metadata.to_owned()); }, link_url, cors_setting, integrity_metadata.to_owned());
} }
fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) { fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {

View file

@ -25,7 +25,8 @@ use script_layout_interface::message::Msg;
use std::cell::Cell; use std::cell::Cell;
use std::sync::Arc; use std::sync::Arc;
use style::media_queries::parse_media_query_list; use style::media_queries::parse_media_query_list;
use style::stylesheets::{Stylesheet, Origin}; use style::parser::ParserContext as CssParserContext;
use style::stylesheets::{CssRuleType, Stylesheet, Origin};
use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; use stylesheet_loader::{StylesheetLoader, StylesheetOwner};
#[dom_struct] #[dom_struct]
@ -73,7 +74,6 @@ impl HTMLStyleElement {
assert!(node.is_in_doc()); assert!(node.is_in_doc());
let win = window_from_node(node); let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media"));
let mq_str = match mq_attribute { let mq_str = match mq_attribute {
@ -82,10 +82,14 @@ impl HTMLStyleElement {
}; };
let data = node.GetTextContent().expect("Element.textContent must be a string"); let data = node.GetTextContent().expect("Element.textContent must be a string");
let mq = parse_media_query_list(&mut CssParser::new(&mq_str)); let url = win.get_url();
let context = CssParserContext::new_for_cssom(&url,
win.css_error_reporter(),
Some(CssRuleType::Media));
let mq = parse_media_query_list(&context, &mut CssParser::new(&mq_str));
let shared_lock = node.owner_doc().style_shared_lock().clone(); let shared_lock = node.owner_doc().style_shared_lock().clone();
let loader = StylesheetLoader::for_element(self.upcast()); let loader = StylesheetLoader::for_element(self.upcast());
let sheet = Stylesheet::from_str(&data, url, Origin::Author, mq, let sheet = Stylesheet::from_str(&data, win.get_url(), Origin::Author, mq,
shared_lock, Some(&loader), shared_lock, Some(&loader),
win.css_error_reporter()); win.css_error_reporter());

View file

@ -7,7 +7,7 @@ use cssparser::Parser;
use dom::bindings::codegen::Bindings::MediaListBinding; use dom::bindings::codegen::Bindings::MediaListBinding;
use dom::bindings::codegen::Bindings::MediaListBinding::MediaListMethods; use dom::bindings::codegen::Bindings::MediaListBinding::MediaListMethods;
use dom::bindings::js::{JS, Root}; use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window; use dom::window::Window;
@ -15,7 +15,9 @@ use dom_struct::dom_struct;
use std::sync::Arc; use std::sync::Arc;
use style::media_queries::{MediaQuery, parse_media_query_list}; use style::media_queries::{MediaQuery, parse_media_query_list};
use style::media_queries::MediaList as StyleMediaList; use style::media_queries::MediaList as StyleMediaList;
use style::parser::ParserContext;
use style::shared_lock::{SharedRwLock, Locked}; use style::shared_lock::{SharedRwLock, Locked};
use style::stylesheets::CssRuleType;
use style_traits::ToCss; use style_traits::ToCss;
#[dom_struct] #[dom_struct]
@ -70,7 +72,11 @@ impl MediaListMethods for MediaList {
} }
// Step 3 // Step 3
let mut parser = Parser::new(&value); let mut parser = Parser::new(&value);
*media_queries = parse_media_query_list(&mut parser); let global = self.global();
let win = global.as_window();
let url = win.get_url();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media));
*media_queries = parse_media_query_list(&context, &mut parser);
} }
// https://drafts.csswg.org/cssom/#dom-medialist-length // https://drafts.csswg.org/cssom/#dom-medialist-length
@ -99,7 +105,11 @@ impl MediaListMethods for MediaList {
fn AppendMedium(&self, medium: DOMString) { fn AppendMedium(&self, medium: DOMString) {
// Step 1 // Step 1
let mut parser = Parser::new(&medium); let mut parser = Parser::new(&medium);
let m = MediaQuery::parse(&mut parser); let global = self.global();
let win = global.as_window();
let url = win.get_url();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media));
let m = MediaQuery::parse(&context, &mut parser);
// Step 2 // Step 2
if let Err(_) = m { if let Err(_) = m {
return; return;
@ -120,7 +130,11 @@ impl MediaListMethods for MediaList {
fn DeleteMedium(&self, medium: DOMString) { fn DeleteMedium(&self, medium: DOMString) {
// Step 1 // Step 1
let mut parser = Parser::new(&medium); let mut parser = Parser::new(&medium);
let m = MediaQuery::parse(&mut parser); let global = self.global();
let win = global.as_window();
let url = win.get_url();
let context = ParserContext::new_for_cssom(&url, win.css_error_reporter(), Some(CssRuleType::Media));
let m = MediaQuery::parse(&context, &mut parser);
// Step 2 // Step 2
if let Err(_) = m { if let Err(_) = m {
return; return;

View file

@ -103,10 +103,12 @@ use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use style::context::ReflowGoal; use style::context::ReflowGoal;
use style::error_reporting::ParseErrorReporter; use style::error_reporting::ParseErrorReporter;
use style::media_queries; use style::media_queries;
use style::parser::ParserContext as CssParserContext;
use style::properties::PropertyId; use style::properties::PropertyId;
use style::properties::longhands::overflow_x; use style::properties::longhands::overflow_x;
use style::selector_parser::PseudoElement; use style::selector_parser::PseudoElement;
use style::str::HTML_SPACE_CHARACTERS; use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::CssRuleType;
use task_source::dom_manipulation::DOMManipulationTaskSource; use task_source::dom_manipulation::DOMManipulationTaskSource;
use task_source::file_reading::FileReadingTaskSource; use task_source::file_reading::FileReadingTaskSource;
use task_source::history_traversal::HistoryTraversalTaskSource; use task_source::history_traversal::HistoryTraversalTaskSource;
@ -963,7 +965,9 @@ impl WindowMethods for Window {
// https://drafts.csswg.org/cssom-view/#dom-window-matchmedia // https://drafts.csswg.org/cssom-view/#dom-window-matchmedia
fn MatchMedia(&self, query: DOMString) -> Root<MediaQueryList> { fn MatchMedia(&self, query: DOMString) -> Root<MediaQueryList> {
let mut parser = Parser::new(&query); let mut parser = Parser::new(&query);
let media_query_list = media_queries::parse_media_query_list(&mut parser); let url = self.get_url();
let context = CssParserContext::new_for_cssom(&url, self.css_error_reporter(), Some(CssRuleType::Media));
let media_query_list = media_queries::parse_media_query_list(&context, &mut parser);
let document = self.Document(); let document = self.Document();
let mql = MediaQueryList::new(&document, media_query_list); let mql = MediaQueryList::new(&document, media_query_list);
self.media_query_lists.push(&*mql); self.media_query_lists.push(&*mql);

View file

@ -14,6 +14,7 @@ use gecko_bindings::structs::{nsMediaExpression_Range, nsMediaFeature};
use gecko_bindings::structs::{nsMediaFeature_ValueType, nsMediaFeature_RangeType, nsMediaFeature_RequirementFlags}; use gecko_bindings::structs::{nsMediaFeature_ValueType, nsMediaFeature_RangeType, nsMediaFeature_RequirementFlags};
use gecko_bindings::structs::RawGeckoPresContextOwned; use gecko_bindings::structs::RawGeckoPresContextOwned;
use media_queries::MediaType; use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues; use properties::ComputedValues;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::fmt::{self, Write}; use std::fmt::{self, Write};
@ -366,7 +367,7 @@ impl Expression {
/// ``` /// ```
/// (media-feature: media-value) /// (media-feature: media-value)
/// ``` /// ```
pub fn parse(input: &mut Parser) -> Result<Self, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
try!(input.expect_parenthesis_block()); try!(input.expect_parenthesis_block());
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let ident = try!(input.expect_ident()); let ident = try!(input.expect_ident());
@ -421,7 +422,7 @@ impl Expression {
let value = match feature.mValueType { let value = match feature.mValueType {
nsMediaFeature_ValueType::eLength => { nsMediaFeature_ValueType::eLength => {
MediaExpressionValue::Length( MediaExpressionValue::Length(
specified::Length::parse_non_negative(input)?) specified::Length::parse_non_negative(context, input)?)
}, },
nsMediaFeature_ValueType::eInteger => { nsMediaFeature_ValueType::eInteger => {
let i = input.expect_integer()?; let i = input.expect_integer()?;

View file

@ -8,6 +8,7 @@
use Atom; use Atom;
use cssparser::{Delimiter, Parser, Token}; use cssparser::{Delimiter, Parser, Token};
use parser::ParserContext;
use serialize_comma_separated_list; use serialize_comma_separated_list;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
use std::fmt; use std::fmt;
@ -23,7 +24,7 @@ pub use gecko::media_queries::{Device, Expression};
#[cfg_attr(feature = "servo", derive(HeapSizeOf))] #[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct MediaList { pub struct MediaList {
/// The list of media queries. /// The list of media queries.
pub media_queries: Vec<MediaQuery> pub media_queries: Vec<MediaQuery>,
} }
impl ToCss for MediaList { impl ToCss for MediaList {
@ -206,7 +207,7 @@ impl MediaQuery {
/// Parse a media query given css input. /// Parse a media query given css input.
/// ///
/// Returns an error if any of the expressions is unknown. /// Returns an error if any of the expressions is unknown.
pub fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<MediaQuery, ()> {
let mut expressions = vec![]; let mut expressions = vec![];
let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() {
@ -226,7 +227,7 @@ impl MediaQuery {
} }
// Without a media type, require at least one expression. // Without a media type, require at least one expression.
expressions.push(try!(Expression::parse(input))); expressions.push(try!(Expression::parse(context, input)));
MediaQueryType::All MediaQueryType::All
} }
@ -237,7 +238,7 @@ impl MediaQuery {
if input.try(|input| input.expect_ident_matching("and")).is_err() { if input.try(|input| input.expect_ident_matching("and")).is_err() {
return Ok(MediaQuery::new(qualifier, media_type, expressions)) return Ok(MediaQuery::new(qualifier, media_type, expressions))
} }
expressions.push(try!(Expression::parse(input))) expressions.push(try!(Expression::parse(context, input)))
} }
} }
} }
@ -248,14 +249,14 @@ impl MediaQuery {
/// media query list is only filled with the equivalent of "not all", see: /// media query list is only filled with the equivalent of "not all", see:
/// ///
/// https://drafts.csswg.org/mediaqueries/#error-handling /// https://drafts.csswg.org/mediaqueries/#error-handling
pub fn parse_media_query_list(input: &mut Parser) -> MediaList { pub fn parse_media_query_list(context: &ParserContext, input: &mut Parser) -> MediaList {
if input.is_exhausted() { if input.is_exhausted() {
return Default::default() return Default::default()
} }
let mut media_queries = vec![]; let mut media_queries = vec![];
loop { loop {
match input.parse_until_before(Delimiter::Comma, MediaQuery::parse) { match input.parse_until_before(Delimiter::Comma, |i| MediaQuery::parse(context, i)) {
Ok(mq) => { Ok(mq) => {
media_queries.push(mq); media_queries.push(mq);
}, },
@ -307,9 +308,9 @@ impl MediaList {
/// https://drafts.csswg.org/cssom/#dom-medialist-appendmedium /// https://drafts.csswg.org/cssom/#dom-medialist-appendmedium
/// ///
/// Returns true if added, false if fail to parse the medium string. /// Returns true if added, false if fail to parse the medium string.
pub fn append_medium(&mut self, new_medium: &str) -> bool { pub fn append_medium(&mut self, context: &ParserContext, new_medium: &str) -> bool {
let mut parser = Parser::new(new_medium); let mut parser = Parser::new(new_medium);
let new_query = match MediaQuery::parse(&mut parser) { let new_query = match MediaQuery::parse(&context, &mut parser) {
Ok(query) => query, Ok(query) => query,
Err(_) => { return false; } Err(_) => { return false; }
}; };
@ -325,9 +326,9 @@ impl MediaList {
/// https://drafts.csswg.org/cssom/#dom-medialist-deletemedium /// https://drafts.csswg.org/cssom/#dom-medialist-deletemedium
/// ///
/// Returns true if found and deleted, false otherwise. /// Returns true if found and deleted, false otherwise.
pub fn delete_medium(&mut self, old_medium: &str) -> bool { pub fn delete_medium(&mut self, context: &ParserContext, old_medium: &str) -> bool {
let mut parser = Parser::new(old_medium); let mut parser = Parser::new(old_medium);
let old_query = match MediaQuery::parse(&mut parser) { let old_query = match MediaQuery::parse(context, &mut parser) {
Ok(query) => query, Ok(query) => query,
Err(_) => { return false; } Err(_) => { return false; }
}; };

View file

@ -482,7 +482,7 @@ ${helpers.single_keyword("background-origin",
}) })
} }
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("cover")).is_ok() { if input.try(|input| input.expect_ident_matching("cover")).is_ok() {
return Ok(SpecifiedValue::Cover); return Ok(SpecifiedValue::Cover);
} }
@ -492,12 +492,12 @@ ${helpers.single_keyword("background-origin",
} }
let width = let width =
try!(specified::LengthOrPercentageOrAuto::parse_non_negative(input)); try!(specified::LengthOrPercentageOrAuto::parse_non_negative(context, input));
let height = if input.is_exhausted() { let height = if input.is_exhausted() {
specified::LengthOrPercentageOrAuto::Auto specified::LengthOrPercentageOrAuto::Auto
} else { } else {
try!(specified::LengthOrPercentageOrAuto::parse_non_negative(input)) try!(specified::LengthOrPercentageOrAuto::parse_non_negative(context, input))
}; };
Ok(SpecifiedValue::Explicit(ExplicitSize { Ok(SpecifiedValue::Explicit(ExplicitSize {

View file

@ -525,16 +525,16 @@ ${helpers.single_keyword("-moz-float-edge", "content-box margin-box",
} }
impl Parse for SingleSpecifiedValue { impl Parse for SingleSpecifiedValue {
fn parse(_context: &ParserContext, 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_non_negative(input)) { if let Ok(len) = input.try(|input| LengthOrPercentage::parse_non_negative(context, input)) {
return Ok(SingleSpecifiedValue::LengthOrPercentage(len)); return Ok(SingleSpecifiedValue::LengthOrPercentage(len));
} }
let num = try!(Number::parse_non_negative(input)); let num = try!(Number::parse_non_negative(context, input));
Ok(SingleSpecifiedValue::Number(num)) Ok(SingleSpecifiedValue::Number(num))
} }
} }

View file

@ -558,20 +558,20 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
} }
impl Parse for SpecifiedValue { impl Parse for SpecifiedValue {
fn parse(_context: &ParserContext, 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" => {
let (mut p1x, mut p1y, mut p2x, mut p2y) = let (mut p1x, mut p1y, mut p2x, mut p2y) =
(Number::new(0.0), Number::new(0.0), Number::new(0.0), Number::new(0.0)); (Number::new(0.0), Number::new(0.0), Number::new(0.0), Number::new(0.0));
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
p1x = try!(specified::parse_number(input)); p1x = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
p1y = try!(specified::parse_number(input)); p1y = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
p2x = try!(specified::parse_number(input)); p2x = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
p2y = try!(specified::parse_number(input)); p2y = try!(specified::parse_number(context, input));
Ok(()) Ok(())
})); }));
if p1x.value < 0.0 || p1x.value > 1.0 || if p1x.value < 0.0 || p1x.value > 1.0 ||
@ -585,7 +585,7 @@ ${helpers.single_keyword("overflow-x", "visible hidden scroll auto",
"steps" => { "steps" => {
let (mut step_count, mut start_end) = (specified::Integer::new(0), StartEnd::End); let (mut step_count, mut start_end) = (specified::Integer::new(0), StartEnd::End);
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
step_count = try!(specified::parse_integer(input)); step_count = try!(specified::parse_integer(context, input));
if step_count.value() < 1 { if step_count.value() < 1 {
return Err(()) return Err(())
} }
@ -1057,12 +1057,12 @@ ${helpers.single_keyword("animation-fill-mode",
} }
} }
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("none")).is_ok() { if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue::None) Ok(SpecifiedValue::None)
} else if input.try(|input| input.expect_function_matching("repeat")).is_ok() { } else if input.try(|input| input.expect_function_matching("repeat")).is_ok() {
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
LengthOrPercentage::parse_non_negative(input).map(SpecifiedValue::Repeat) LengthOrPercentage::parse_non_negative(context, input).map(SpecifiedValue::Repeat)
}) })
} else { } else {
Err(()) Err(())
@ -1349,7 +1349,7 @@ ${helpers.predefined_type("scroll-snap-coordinate",
"matrix" => { "matrix" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let values = try!(input.parse_comma_separated(|input| { let values = try!(input.parse_comma_separated(|input| {
specified::parse_number(input) specified::parse_number(context, input)
})); }));
if values.len() != 6 { if values.len() != 6 {
return Err(()) return Err(())
@ -1367,7 +1367,7 @@ ${helpers.predefined_type("scroll-snap-coordinate",
}, },
"matrix3d" => { "matrix3d" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let values = try!(input.parse_comma_separated(specified::parse_number)); let values = try!(input.parse_comma_separated(|i| specified::parse_number(context, i)));
if values.len() != 16 { if values.len() != 16 {
return Err(()) return Err(())
} }
@ -1426,9 +1426,9 @@ ${helpers.predefined_type("scroll-snap-coordinate",
}, },
"scale" => { "scale" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(input)); let sx = try!(specified::parse_number(context, input));
if input.try(|input| input.expect_comma()).is_ok() { if input.try(|input| input.expect_comma()).is_ok() {
let sy = try!(specified::parse_number(input)); let sy = try!(specified::parse_number(context, input));
result.push(SpecifiedOperation::Scale(sx, Some(sy))); result.push(SpecifiedOperation::Scale(sx, Some(sy)));
} else { } else {
result.push(SpecifiedOperation::Scale(sx, None)); result.push(SpecifiedOperation::Scale(sx, None));
@ -1438,32 +1438,32 @@ ${helpers.predefined_type("scroll-snap-coordinate",
}, },
"scalex" => { "scalex" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(input)); let sx = try!(specified::parse_number(context, input));
result.push(SpecifiedOperation::ScaleX(sx)); result.push(SpecifiedOperation::ScaleX(sx));
Ok(()) Ok(())
})) }))
}, },
"scaley" => { "scaley" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let sy = try!(specified::parse_number(input)); let sy = try!(specified::parse_number(context, input));
result.push(SpecifiedOperation::ScaleY(sy)); result.push(SpecifiedOperation::ScaleY(sy));
Ok(()) Ok(())
})) }))
}, },
"scalez" => { "scalez" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let sz = try!(specified::parse_number(input)); let sz = try!(specified::parse_number(context, input));
result.push(SpecifiedOperation::ScaleZ(sz)); result.push(SpecifiedOperation::ScaleZ(sz));
Ok(()) Ok(())
})) }))
}, },
"scale3d" => { "scale3d" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let sx = try!(specified::parse_number(input)); let sx = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let sy = try!(specified::parse_number(input)); let sy = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let sz = try!(specified::parse_number(input)); let sz = try!(specified::parse_number(context, input));
result.push(SpecifiedOperation::Scale3D(sx, sy, sz)); result.push(SpecifiedOperation::Scale3D(sx, sy, sz));
Ok(()) Ok(())
})) }))
@ -1498,11 +1498,11 @@ ${helpers.predefined_type("scroll-snap-coordinate",
}, },
"rotate3d" => { "rotate3d" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let ax = try!(specified::parse_number(input)); let ax = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let ay = try!(specified::parse_number(input)); let ay = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let az = try!(specified::parse_number(input)); let az = try!(specified::parse_number(context, input));
try!(input.expect_comma()); try!(input.expect_comma());
let theta = try!(specified::Angle::parse_with_unitless(context,input)); let theta = try!(specified::Angle::parse_with_unitless(context,input));
// TODO(gw): Check the axis can be normalized!! // TODO(gw): Check the axis can be normalized!!
@ -1538,7 +1538,7 @@ ${helpers.predefined_type("scroll-snap-coordinate",
}, },
"perspective" => { "perspective" => {
try!(input.parse_nested_block(|input| { try!(input.parse_nested_block(|input| {
let d = try!(specified::Length::parse_non_negative(input)); let d = try!(specified::Length::parse_non_negative(context, input));
result.push(SpecifiedOperation::Perspective(d)); result.push(SpecifiedOperation::Perspective(d));
Ok(()) Ok(())
})) }))

View file

@ -330,11 +330,11 @@
} }
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
parse_common(1, input) parse_common(context, 1, input)
} }
pub fn parse_common(default_value: i32, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse_common(context: &ParserContext, default_value: i32, 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()))
} }
@ -349,8 +349,8 @@
if content::counter_name_is_illegal(&counter_name) { if content::counter_name_is_illegal(&counter_name) {
return Err(()) return Err(())
} }
let counter_delta = let counter_delta = input.try(|input| specified::parse_integer(context, input))
input.try(|input| specified::parse_integer(input)).unwrap_or(specified::Integer::new(default_value)); .unwrap_or(specified::Integer::new(default_value));
counters.push((counter_name, counter_delta)) counters.push((counter_name, counter_delta))
} }
@ -367,7 +367,7 @@
pub use super::counter_increment::{SpecifiedValue, computed_value, get_initial_value}; pub use super::counter_increment::{SpecifiedValue, computed_value, get_initial_value};
use super::counter_increment::parse_common; use super::counter_increment::parse_common;
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
parse_common(0, input) parse_common(context, 0, input)
} }
</%helpers:longhand> </%helpers:longhand>

View file

@ -339,7 +339,7 @@ ${helpers.predefined_type("clip",
if let Ok(function_name) = input.try(|input| input.expect_function()) { if let Ok(function_name) = input.try(|input| input.expect_function()) {
filters.push(try!(input.parse_nested_block(|input| { filters.push(try!(input.parse_nested_block(|input| {
match_ignore_ascii_case! { &function_name, match_ignore_ascii_case! { &function_name,
"blur" => specified::Length::parse_non_negative(input).map(SpecifiedFilter::Blur), "blur" => specified::Length::parse_non_negative(context, input).map(SpecifiedFilter::Blur),
"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),

View file

@ -659,8 +659,8 @@ ${helpers.single_keyword("font-variant-caps",
} }
} }
/// <length> | <percentage> | <absolute-size> | <relative-size> /// <length> | <percentage> | <absolute-size> | <relative-size>
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if let Ok(lop) = input.try(specified::LengthOrPercentage::parse_non_negative) { if let Ok(lop) = input.try(|i| specified::LengthOrPercentage::parse_non_negative(context, i)) {
return Ok(SpecifiedValue::Length(lop)) return Ok(SpecifiedValue::Length(lop))
} }
@ -766,14 +766,14 @@ ${helpers.single_keyword("font-variant-caps",
} }
/// none | <number> /// none | <number>
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use values::specified::Number; use values::specified::Number;
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::None); return Ok(SpecifiedValue::None);
} }
Ok(SpecifiedValue::Number(try!(Number::parse_non_negative(input)))) Ok(SpecifiedValue::Number(try!(Number::parse_non_negative(context, input))))
} }
</%helpers:longhand> </%helpers:longhand>

View file

@ -71,7 +71,6 @@ ${helpers.predefined_type(
"parse_numbers_are_pixels_non_negative", "parse_numbers_are_pixels_non_negative",
products="gecko", products="gecko",
animation_type="normal", animation_type="normal",
needs_context=False,
spec="https://www.w3.org/TR/SVG2/painting.html#StrokeWidth")} spec="https://www.w3.org/TR/SVG2/painting.html#StrokeWidth")}
${helpers.single_keyword("stroke-linecap", "butt round square", ${helpers.single_keyword("stroke-linecap", "butt round square",
@ -84,7 +83,6 @@ ${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,
animation_type="none", animation_type="none",
spec="https://www.w3.org/TR/SVG11/painting.html#StrokeMiterlimitProperty")} spec="https://www.w3.org/TR/SVG11/painting.html#StrokeMiterlimitProperty")}
@ -108,7 +106,6 @@ ${helpers.predefined_type(
"parse_numbers_are_pixels", "parse_numbers_are_pixels",
products="gecko", products="gecko",
animation_type="normal", animation_type="normal",
needs_context=False,
spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing")} spec="https://www.w3.org/TR/SVG2/painting.html#StrokeDashing")}
// Section 14 - Clipping, Masking and Compositing // Section 14 - Clipping, Masking and Compositing

View file

@ -114,14 +114,14 @@ ${helpers.single_keyword("caption-side", "top bottom",
} }
} }
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
let mut first = None; let mut first = None;
let mut second = None; let mut second = None;
match specified::Length::parse_non_negative(input) { match specified::Length::parse_non_negative(context, input) {
Err(()) => (), Err(()) => (),
Ok(length) => { Ok(length) => {
first = Some(length); first = Some(length);
if let Ok(len) = input.try(|input| specified::Length::parse_non_negative(input)) { if let Ok(len) = input.try(|input| specified::Length::parse_non_negative(context, input)) {
second = Some(len); second = Some(len);
} }
} }

View file

@ -45,18 +45,18 @@
} }
} }
/// normal | <number> | <length> | <percentage> /// normal | <number> | <length> | <percentage>
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use cssparser::Token; use cssparser::Token;
use std::ascii::AsciiExt; use std::ascii::AsciiExt;
// We try to parse as a Number first because, for 'line-height', we want // We try to parse as a Number first because, for 'line-height', we want
// "0" to be parsed as a plain Number rather than a Length (0px); this // "0" to be parsed as a plain Number rather than a Length (0px); this
// matches the behaviour of all major browsers // matches the behaviour of all major browsers
if let Ok(number) = input.try(specified::Number::parse_non_negative) { if let Ok(number) = input.try(|i| specified::Number::parse_non_negative(context, i)) {
return Ok(SpecifiedValue::Number(number)) return Ok(SpecifiedValue::Number(number))
} }
if let Ok(lop) = input.try(specified::LengthOrPercentage::parse_non_negative) { if let Ok(lop) = input.try(|i| specified::LengthOrPercentage::parse_non_negative(context, i)) {
return Ok(SpecifiedValue::LengthOrPercentage(lop)) return Ok(SpecifiedValue::LengthOrPercentage(lop))
} }

View file

@ -77,8 +77,8 @@ ${helpers.predefined_type("outline-color", "CSSColor", "computed::CSSColor::Curr
} }
} }
pub fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue) specified::parse_border_width(context, input).map(SpecifiedValue)
} }
impl HasViewportPercentage for SpecifiedValue { impl HasViewportPercentage for SpecifiedValue {

View file

@ -16,7 +16,6 @@
"computed::LengthOrPercentage::Length(Au(0))", "computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative", "parse_non_negative",
alias=maybe_moz_logical_alias(product, side, "-moz-padding-%s"), alias=maybe_moz_logical_alias(product, side, "-moz-padding-%s"),
needs_context=False,
animation_type="normal", animation_type="normal",
logical = side[1], logical = side[1],
spec = spec)} spec = spec)}

View file

@ -95,14 +95,12 @@ ${helpers.predefined_type("flex-grow", "Number",
"0.0", "parse_non_negative", "0.0", "parse_non_negative",
spec="https://drafts.csswg.org/css-flexbox/#flex-grow-property", spec="https://drafts.csswg.org/css-flexbox/#flex-grow-property",
extra_prefixes="webkit", extra_prefixes="webkit",
needs_context=False,
animation_type="normal")} animation_type="normal")}
${helpers.predefined_type("flex-shrink", "Number", ${helpers.predefined_type("flex-shrink", "Number",
"1.0", "parse_non_negative", "1.0", "parse_non_negative",
spec="https://drafts.csswg.org/css-flexbox/#flex-shrink-property", spec="https://drafts.csswg.org/css-flexbox/#flex-shrink-property",
extra_prefixes="webkit", extra_prefixes="webkit",
needs_context=False,
animation_type="normal")} animation_type="normal")}
// https://drafts.csswg.org/css-align/#align-self-property // https://drafts.csswg.org/css-align/#align-self-property
@ -142,7 +140,6 @@ ${helpers.predefined_type("flex-basis",
"computed::LengthOrPercentageOrAuto::Auto" if product == "gecko" else "computed::LengthOrPercentageOrAuto::Auto" if product == "gecko" else
"computed::LengthOrPercentageOrAutoOrContent::Auto", "computed::LengthOrPercentageOrAutoOrContent::Auto",
"parse_non_negative", "parse_non_negative",
needs_context=False,
spec="https://drafts.csswg.org/css-flexbox/#flex-basis-property", spec="https://drafts.csswg.org/css-flexbox/#flex-basis-property",
extra_prefixes="webkit", extra_prefixes="webkit",
animation_type="normal" if product == "gecko" else "none")} animation_type="normal" if product == "gecko" else "none")}
@ -158,7 +155,6 @@ ${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAuto", "LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto", "computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative", "parse_non_negative",
needs_context=False,
spec=spec % size, spec=spec % size,
animation_type="normal", logical = logical)} animation_type="normal", logical = logical)}
% if product == "gecko": % if product == "gecko":
@ -255,14 +251,12 @@ ${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,
spec=spec % ("min-%s" % size), spec=spec % ("min-%s" % size),
animation_type="normal", logical = logical)} animation_type="normal", logical = logical)}
${helpers.predefined_type("max-%s" % size, ${helpers.predefined_type("max-%s" % size,
"LengthOrPercentageOrNone", "LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None", "computed::LengthOrPercentageOrNone::None",
"parse_non_negative", "parse_non_negative",
needs_context=False,
spec=spec % ("min-%s" % size), spec=spec % ("min-%s" % size),
animation_type="normal", logical = logical)} animation_type="normal", logical = logical)}
% endif % endif

View file

@ -288,7 +288,7 @@ ${helpers.predefined_type(
return Ok(SpecifiedValue::Normal); return Ok(SpecifiedValue::Normal);
} }
let size = try!(Number::parse_at_least_one(input)); let size = try!(Number::parse_at_least_one(context, input));
match input.try(|input| Integer::parse(context, input)) { match input.try(|input| Integer::parse(context, input)) {
Ok(number) => { Ok(number) => {

View file

@ -25,7 +25,6 @@ ${helpers.single_keyword("-moz-box-direction", "normal reverse",
${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,
animation_type="none", animation_type="none",
alias="-webkit-box-flex", alias="-webkit-box-flex",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-flex)")} spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-flex)")}
@ -52,7 +51,6 @@ ${helpers.single_keyword("-moz-stack-sizing", "stretch-to-fit ignore",
${helpers.predefined_type("-moz-box-ordinal-group", "Integer", "0", ${helpers.predefined_type("-moz-box-ordinal-group", "Integer", "0",
parse_method="parse_non_negative", parse_method="parse_non_negative",
needs_context=False,
products="gecko", products="gecko",
alias="-webkit-box-ordinal-group", alias="-webkit-box-ordinal-group",
gecko_ffi_name="mBoxOrdinal", gecko_ffi_name="mBoxOrdinal",

View file

@ -50,10 +50,10 @@
spec="https://drafts.csswg.org/css-flexbox/#flex-property"> spec="https://drafts.csswg.org/css-flexbox/#flex-property">
use values::specified::Number; use values::specified::Number;
fn parse_flexibility(input: &mut Parser) fn parse_flexibility(context: &ParserContext, input: &mut Parser)
-> Result<(Number, Option<Number>),()> { -> Result<(Number, Option<Number>),()> {
let grow = try!(Number::parse_non_negative(input)); let grow = try!(Number::parse_non_negative(context, input));
let shrink = input.try(Number::parse_non_negative).ok(); let shrink = input.try(|i| Number::parse_non_negative(context, i)).ok();
Ok((grow, shrink)) Ok((grow, shrink))
} }
@ -71,7 +71,7 @@
} }
loop { loop {
if grow.is_none() { if grow.is_none() {
if let Ok((flex_grow, flex_shrink)) = input.try(parse_flexibility) { if let Ok((flex_grow, flex_shrink)) = input.try(|i| parse_flexibility(context, i)) {
grow = Some(flex_grow); grow = Some(flex_grow);
shrink = flex_shrink; shrink = flex_shrink;
continue continue

View file

@ -9,6 +9,7 @@ use cssparser::Parser;
use euclid::{Size2D, TypedSize2D}; use euclid::{Size2D, TypedSize2D};
use font_metrics::ServoMetricsProvider; use font_metrics::ServoMetricsProvider;
use media_queries::MediaType; use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues; use properties::ComputedValues;
use std::fmt; use std::fmt;
use style_traits::{CSSPixel, ToCss}; use style_traits::{CSSPixel, ToCss};
@ -104,7 +105,7 @@ impl Expression {
/// ``` /// ```
/// ///
/// Only supports width and width ranges for now. /// Only supports width and width ranges for now.
pub fn parse(input: &mut Parser) -> Result<Self, ()> { pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
try!(input.expect_parenthesis_block()); try!(input.expect_parenthesis_block());
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
let name = try!(input.expect_ident()); let name = try!(input.expect_ident());
@ -112,13 +113,13 @@ impl Expression {
// TODO: Handle other media features // TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name, Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => { "min-width" => {
ExpressionKind::Width(Range::Min(try!(specified::Length::parse_non_negative(input)))) ExpressionKind::Width(Range::Min(try!(specified::Length::parse_non_negative(context, input))))
}, },
"max-width" => { "max-width" => {
ExpressionKind::Width(Range::Max(try!(specified::Length::parse_non_negative(input)))) ExpressionKind::Width(Range::Max(try!(specified::Length::parse_non_negative(context, input))))
}, },
"width" => { "width" => {
ExpressionKind::Width(Range::Eq(try!(specified::Length::parse_non_negative(input)))) ExpressionKind::Width(Range::Eq(try!(specified::Length::parse_non_negative(context, input))))
}, },
_ => return Err(()) _ => return Err(())
})) }))

View file

@ -905,7 +905,7 @@ impl<'a> AtRuleParser for TopLevelRuleParser<'a> {
let url_string = input.expect_url_or_string()?; let url_string = input.expect_url_or_string()?;
let specified_url = SpecifiedUrl::parse_from_string(url_string, &self.context)?; let specified_url = SpecifiedUrl::parse_from_string(url_string, &self.context)?;
let media = parse_media_query_list(input); let media = parse_media_query_list(&self.context, input);
let noop_loader = NoOpLoader; let noop_loader = NoOpLoader;
let loader = if !specified_url.is_invalid() { let loader = if !specified_url.is_invalid() {
@ -1054,7 +1054,7 @@ impl<'a, 'b> AtRuleParser for NestedRuleParser<'a, 'b> {
-> Result<AtRuleType<AtRulePrelude, CssRule>, ()> { -> Result<AtRuleType<AtRulePrelude, CssRule>, ()> {
match_ignore_ascii_case! { name, match_ignore_ascii_case! { name,
"media" => { "media" => {
let media_queries = parse_media_query_list(input); let media_queries = parse_media_query_list(self.context, input);
let arc = Arc::new(self.shared_lock.wrap(media_queries)); let arc = Arc::new(self.shared_lock.wrap(media_queries));
Ok(AtRuleType::WithBlock(AtRulePrelude::Media(arc))) Ok(AtRuleType::WithBlock(AtRulePrelude::Media(arc)))
}, },

View file

@ -662,8 +662,8 @@ impl Default for ShapeRadius {
} }
impl Parse for ShapeRadius { impl Parse for ShapeRadius {
fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
input.try(|i| LengthOrPercentage::parse_non_negative(i)).map(ShapeRadius::Length).or_else(|_| { input.try(|i| LengthOrPercentage::parse_non_negative(context, i)).map(ShapeRadius::Length).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),
@ -749,10 +749,10 @@ impl ToCss for BorderRadius {
} }
impl Parse for BorderRadius { impl Parse for BorderRadius {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let mut widths = try!(parse_one_set_of_border_values(input)); let mut widths = try!(parse_one_set_of_border_values(context, input));
let mut heights = if input.try(|input| input.expect_delim('/')).is_ok() { let mut 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[0].clone(), [widths[0].clone(),
widths[1].clone(), widths[1].clone(),
@ -768,22 +768,22 @@ 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_non_negative(input)); let a = try!(LengthOrPercentage::parse_non_negative(context, input));
let b = if let Ok(b) = input.try(|i| LengthOrPercentage::parse_non_negative(i)) { let b = if let Ok(b) = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) {
b b
} else { } else {
return Ok([a.clone(), a.clone(), a.clone(), a]) return Ok([a.clone(), a.clone(), a.clone(), a])
}; };
let c = if let Ok(c) = input.try(|i| LengthOrPercentage::parse_non_negative(i)) { let c = if let Ok(c) = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) {
c c
} else { } else {
return Ok([a.clone(), b.clone(), a, b]) return Ok([a.clone(), b.clone(), a, b])
}; };
if let Ok(d) = input.try(|i| LengthOrPercentage::parse_non_negative(i)) { if let Ok(d) = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) {
Ok([a, b, c, d]) Ok([a, b, c, d])
} else { } else {
Ok([a, b.clone(), c, b]) Ok([a, b.clone(), c, b])

View file

@ -138,8 +138,8 @@ pub fn parse_flex(input: &mut Parser) -> Result<CSSFloat, ()> {
} }
impl Parse for TrackBreadth<LengthOrPercentage> { impl Parse for TrackBreadth<LengthOrPercentage> {
fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(lop) = input.try(LengthOrPercentage::parse_non_negative) { if let Ok(lop) = input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) {
return Ok(TrackBreadth::Breadth(lop)) return Ok(TrackBreadth::Breadth(lop))
} }
@ -230,7 +230,7 @@ impl Parse for TrackSize<LengthOrPercentage> {
if input.try(|i| i.expect_function_matching("minmax")).is_ok() { if input.try(|i| i.expect_function_matching("minmax")).is_ok() {
return input.parse_nested_block(|input| { return input.parse_nested_block(|input| {
let inflexible_breadth = let inflexible_breadth =
match input.try(LengthOrPercentage::parse_non_negative) { match input.try(|i| LengthOrPercentage::parse_non_negative(context, i)) {
Ok(lop) => TrackBreadth::Breadth(lop), Ok(lop) => TrackBreadth::Breadth(lop),
Err(..) => { Err(..) => {
let keyword = try!(TrackKeyword::parse(input)); let keyword = try!(TrackKeyword::parse(input));

View file

@ -373,7 +373,7 @@ impl Mul<CSSFloat> for NoCalcLength {
impl NoCalcLength { impl NoCalcLength {
/// Parse a given absolute or relative dimension. /// Parse a given absolute or relative dimension.
pub fn parse_dimension(value: CSSFloat, unit: &str) -> Result<NoCalcLength, ()> { pub fn parse_dimension(_context: &ParserContext, value: CSSFloat, unit: &str) -> Result<NoCalcLength, ()> {
match_ignore_ascii_case! { unit, match_ignore_ascii_case! { unit,
"px" => Ok(NoCalcLength::Absolute(AbsoluteLength::Px(value))), "px" => Ok(NoCalcLength::Absolute(AbsoluteLength::Px(value))),
"in" => Ok(NoCalcLength::Absolute(AbsoluteLength::In(value))), "in" => Ok(NoCalcLength::Absolute(AbsoluteLength::In(value))),
@ -512,19 +512,20 @@ impl Length {
} }
/// Parse a given absolute or relative dimension. /// Parse a given absolute or relative dimension.
pub fn parse_dimension(value: CSSFloat, unit: &str) -> Result<Length, ()> { pub fn parse_dimension(context: &ParserContext, value: CSSFloat, unit: &str) -> Result<Length, ()> {
NoCalcLength::parse_dimension(value, unit).map(Length::NoCalc) NoCalcLength::parse_dimension(context, value, unit).map(Length::NoCalc)
} }
#[inline] #[inline]
fn parse_internal(input: &mut Parser, context: AllowedNumericType) -> Result<Length, ()> { fn parse_internal(context: &ParserContext, input: &mut Parser, num_context: AllowedNumericType)
-> Result<Length, ()> {
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 num_context.is_ok(value.value) =>
Length::parse_dimension(value.value, unit), Length::parse_dimension(context, value.value, unit),
Token::Number(ref value) if value.value == 0. => Ok(Length::zero()), Token::Number(ref value) if value.value == 0. => Ok(Length::zero()),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => Token::Function(ref name) if name.eq_ignore_ascii_case("calc") =>
input.parse_nested_block(|input| { input.parse_nested_block(|input| {
CalcLengthOrPercentage::parse_length(input, context) CalcLengthOrPercentage::parse_length(context, input, num_context)
}), }),
_ => Err(()) _ => Err(())
} }
@ -532,8 +533,8 @@ impl Length {
/// Parse a non-negative length /// Parse a non-negative length
#[inline] #[inline]
pub fn parse_non_negative(input: &mut Parser) -> Result<Length, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Length, ()> {
Self::parse_internal(input, AllowedNumericType::NonNegative) Self::parse_internal(context, input, AllowedNumericType::NonNegative)
} }
/// Get an absolute length from a px value. /// Get an absolute length from a px value.
@ -552,8 +553,8 @@ impl Length {
} }
impl Parse for Length { impl Parse for Length {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Self::parse_internal(input, AllowedNumericType::All) Self::parse_internal(context, input, AllowedNumericType::All)
} }
} }
@ -564,7 +565,7 @@ impl Either<Length, None_> {
if input.try(|input| None_::parse(context, input)).is_ok() { if input.try(|input| None_::parse(context, input)).is_ok() {
return Ok(Either::Second(None_)); return Ok(Either::Second(None_));
} }
Length::parse_non_negative(input).map(Either::First) Length::parse_non_negative(context, input).map(Either::First)
} }
} }
@ -575,7 +576,7 @@ impl Either<Length, Normal> {
if input.try(|input| Normal::parse(context, input)).is_ok() { if input.try(|input| Normal::parse(context, input)).is_ok() {
return Ok(Either::Second(Normal)); return Ok(Either::Second(Normal));
} }
Length::parse_internal(input, AllowedNumericType::NonNegative).map(Either::First) Length::parse_internal(context, input, AllowedNumericType::NonNegative).map(Either::First)
} }
} }
@ -586,7 +587,7 @@ impl Either<Length, Auto> {
if input.try(|input| Auto::parse(context, input)).is_ok() { if input.try(|input| Auto::parse(context, input)).is_ok() {
return Ok(Either::Second(Auto)); return Ok(Either::Second(Auto));
} }
Length::parse_internal(input, AllowedNumericType::NonNegative).map(Either::First) Length::parse_internal(context, input, AllowedNumericType::NonNegative).map(Either::First)
} }
} }
@ -645,9 +646,9 @@ pub struct CalcLengthOrPercentage {
impl CalcLengthOrPercentage { impl CalcLengthOrPercentage {
/// Parse a calc sum node. /// Parse a calc sum node.
pub fn parse_sum(input: &mut Parser, expected_unit: CalcUnit) -> Result<CalcSumNode, ()> { pub fn parse_sum(context: &ParserContext, input: &mut Parser, expected_unit: CalcUnit) -> Result<CalcSumNode, ()> {
let mut products = Vec::new(); let mut products = Vec::new();
products.push(try!(CalcLengthOrPercentage::parse_product(input, expected_unit))); products.push(try!(CalcLengthOrPercentage::parse_product(context, input, expected_unit)));
loop { loop {
let position = input.position(); let position = input.position();
@ -658,10 +659,10 @@ impl CalcLengthOrPercentage {
} }
match input.next() { match input.next() {
Ok(Token::Delim('+')) => { Ok(Token::Delim('+')) => {
products.push(try!(CalcLengthOrPercentage::parse_product(input, expected_unit))); products.push(try!(CalcLengthOrPercentage::parse_product(context, input, expected_unit)));
} }
Ok(Token::Delim('-')) => { Ok(Token::Delim('-')) => {
let mut right = try!(CalcLengthOrPercentage::parse_product(input, expected_unit)); let mut right = try!(CalcLengthOrPercentage::parse_product(context, input, expected_unit));
right.values.push(CalcValueNode::Number(-1.)); right.values.push(CalcValueNode::Number(-1.));
products.push(right); products.push(right);
} }
@ -679,15 +680,16 @@ impl CalcLengthOrPercentage {
Ok(CalcSumNode { products: products }) Ok(CalcSumNode { products: products })
} }
fn parse_product(input: &mut Parser, expected_unit: CalcUnit) -> Result<CalcProductNode, ()> { fn parse_product(context: &ParserContext, input: &mut Parser, expected_unit: CalcUnit)
-> Result<CalcProductNode, ()> {
let mut values = Vec::new(); let mut values = Vec::new();
values.push(try!(CalcLengthOrPercentage::parse_value(input, expected_unit))); values.push(try!(CalcLengthOrPercentage::parse_value(context, input, expected_unit)));
loop { loop {
let position = input.position(); let position = input.position();
match input.next() { match input.next() {
Ok(Token::Delim('*')) => { Ok(Token::Delim('*')) => {
values.push(try!(CalcLengthOrPercentage::parse_value(input, expected_unit))); values.push(try!(CalcLengthOrPercentage::parse_value(context, input, expected_unit)));
} }
Ok(Token::Delim('/')) if expected_unit != CalcUnit::Integer => { Ok(Token::Delim('/')) if expected_unit != CalcUnit::Integer => {
if let Ok(Token::Number(ref value)) = input.next() { if let Ok(Token::Number(ref value)) = input.next() {
@ -709,12 +711,12 @@ impl CalcLengthOrPercentage {
Ok(CalcProductNode { values: values }) Ok(CalcProductNode { values: values })
} }
fn parse_value(input: &mut Parser, expected_unit: CalcUnit) -> Result<CalcValueNode, ()> { fn parse_value(context: &ParserContext, input: &mut Parser, expected_unit: CalcUnit) -> Result<CalcValueNode, ()> {
match (try!(input.next()), expected_unit) { match (try!(input.next()), expected_unit) {
(Token::Number(ref value), _) => Ok(CalcValueNode::Number(value.value)), (Token::Number(ref value), _) => Ok(CalcValueNode::Number(value.value)),
(Token::Dimension(ref value, ref unit), CalcUnit::Length) | (Token::Dimension(ref value, ref unit), CalcUnit::Length) |
(Token::Dimension(ref value, ref unit), CalcUnit::LengthOrPercentage) => { (Token::Dimension(ref value, ref unit), CalcUnit::LengthOrPercentage) => {
NoCalcLength::parse_dimension(value.value, unit).map(CalcValueNode::Length) NoCalcLength::parse_dimension(context, value.value, unit).map(CalcValueNode::Length)
} }
(Token::Dimension(ref value, ref unit), CalcUnit::Angle) => { (Token::Dimension(ref value, ref unit), CalcUnit::Angle) => {
Angle::parse_dimension(value.value, unit).map(|angle| { Angle::parse_dimension(value.value, unit).map(|angle| {
@ -729,7 +731,7 @@ impl CalcLengthOrPercentage {
(Token::Percentage(ref value), CalcUnit::LengthOrPercentage) => (Token::Percentage(ref value), CalcUnit::LengthOrPercentage) =>
Ok(CalcValueNode::Percentage(value.unit_value)), Ok(CalcValueNode::Percentage(value.unit_value)),
(Token::ParenthesisBlock, _) => { (Token::ParenthesisBlock, _) => {
input.parse_nested_block(|i| CalcLengthOrPercentage::parse_sum(i, expected_unit)) input.parse_nested_block(|i| CalcLengthOrPercentage::parse_sum(context, i, expected_unit))
.map(|result| CalcValueNode::Sum(Box::new(result))) .map(|result| CalcValueNode::Sum(Box::new(result)))
}, },
_ => Err(()) _ => Err(())
@ -810,21 +812,23 @@ impl CalcLengthOrPercentage {
} }
} }
fn parse_length(input: &mut Parser, fn parse_length(context: &ParserContext,
context: AllowedNumericType) -> Result<Length, ()> { input: &mut Parser,
CalcLengthOrPercentage::parse(input, CalcUnit::Length).map(|calc| { num_context: AllowedNumericType) -> Result<Length, ()> {
Length::Calc(Box::new(calc), context) CalcLengthOrPercentage::parse(context, input, CalcUnit::Length).map(|calc| {
Length::Calc(Box::new(calc), num_context)
}) })
} }
fn parse_length_or_percentage(input: &mut Parser) -> Result<CalcLengthOrPercentage, ()> { fn parse_length_or_percentage(context: &ParserContext, input: &mut Parser) -> Result<CalcLengthOrPercentage, ()> {
CalcLengthOrPercentage::parse(input, CalcUnit::LengthOrPercentage) CalcLengthOrPercentage::parse(context, input, CalcUnit::LengthOrPercentage)
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse(input: &mut Parser, pub fn parse(context: &ParserContext,
input: &mut Parser,
expected_unit: CalcUnit) -> Result<CalcLengthOrPercentage, ()> { expected_unit: CalcUnit) -> Result<CalcLengthOrPercentage, ()> {
let ast = try!(CalcLengthOrPercentage::parse_sum(input, expected_unit)); let ast = try!(CalcLengthOrPercentage::parse_sum(context, input, expected_unit));
let mut simplified = Vec::new(); let mut simplified = Vec::new();
for ref node in ast.products { for ref node in ast.products {
@ -893,8 +897,8 @@ impl CalcLengthOrPercentage {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_time(input: &mut Parser) -> Result<Time, ()> { pub fn parse_time(context: &ParserContext, input: &mut Parser) -> Result<Time, ()> {
let ast = try!(CalcLengthOrPercentage::parse_sum(input, CalcUnit::Time)); let ast = try!(CalcLengthOrPercentage::parse_sum(context, input, CalcUnit::Time));
let mut simplified = Vec::new(); let mut simplified = Vec::new();
for ref node in ast.products { for ref node in ast.products {
@ -921,8 +925,8 @@ impl CalcLengthOrPercentage {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_angle(input: &mut Parser) -> Result<Angle, ()> { pub fn parse_angle(context: &ParserContext, input: &mut Parser) -> Result<Angle, ()> {
let ast = try!(CalcLengthOrPercentage::parse_sum(input, CalcUnit::Angle)); let ast = try!(CalcLengthOrPercentage::parse_sum(context, input, CalcUnit::Angle));
let mut simplified = Vec::new(); let mut simplified = Vec::new();
for ref node in ast.products { for ref node in ast.products {
@ -1119,18 +1123,20 @@ impl LengthOrPercentage {
LengthOrPercentage::Length(NoCalcLength::zero()) LengthOrPercentage::Length(NoCalcLength::zero())
} }
fn parse_internal(input: &mut Parser, context: AllowedNumericType) fn parse_internal(context: &ParserContext, input: &mut Parser, num_context: AllowedNumericType)
-> Result<LengthOrPercentage, ()> -> Result<LengthOrPercentage, ()>
{ {
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 num_context.is_ok(value.value) =>
NoCalcLength::parse_dimension(value.value, unit).map(LengthOrPercentage::Length), NoCalcLength::parse_dimension(context, value.value, unit).map(LengthOrPercentage::Length),
Token::Percentage(ref value) if context.is_ok(value.unit_value) => Token::Percentage(ref value) if num_context.is_ok(value.unit_value) =>
Ok(LengthOrPercentage::Percentage(Percentage(value.unit_value))), Ok(LengthOrPercentage::Percentage(Percentage(value.unit_value))),
Token::Number(ref value) if value.value == 0. => Token::Number(ref value) if value.value == 0. =>
Ok(LengthOrPercentage::zero()), Ok(LengthOrPercentage::zero()),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = try!(input.parse_nested_block(CalcLengthOrPercentage::parse_length_or_percentage)); let calc = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_length_or_percentage(context, i)
}));
Ok(LengthOrPercentage::Calc(Box::new(calc))) Ok(LengthOrPercentage::Calc(Box::new(calc)))
}, },
_ => Err(()) _ => Err(())
@ -1139,15 +1145,15 @@ impl LengthOrPercentage {
/// Parse a non-negative length. /// Parse a non-negative length.
#[inline] #[inline]
pub fn parse_non_negative(input: &mut Parser) -> Result<LengthOrPercentage, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<LengthOrPercentage, ()> {
Self::parse_internal(input, AllowedNumericType::NonNegative) Self::parse_internal(context, input, AllowedNumericType::NonNegative)
} }
/// Parse a length, treating dimensionless numbers as pixels /// Parse a length, treating dimensionless numbers as pixels
/// ///
/// https://www.w3.org/TR/SVG2/types.html#presentation-attribute-css-value /// https://www.w3.org/TR/SVG2/types.html#presentation-attribute-css-value
pub fn parse_numbers_are_pixels(input: &mut Parser) -> Result<LengthOrPercentage, ()> { pub fn parse_numbers_are_pixels(context: &ParserContext, input: &mut Parser) -> Result<LengthOrPercentage, ()> {
if let Ok(lop) = input.try(|i| Self::parse_internal(i, AllowedNumericType::All)) { if let Ok(lop) = input.try(|i| Self::parse_internal(context, i, AllowedNumericType::All)) {
return Ok(lop) return Ok(lop)
} }
@ -1160,8 +1166,10 @@ impl LengthOrPercentage {
/// Parse a non-negative length, treating dimensionless numbers as pixels /// Parse a non-negative length, treating dimensionless numbers as pixels
/// ///
/// This is nonstandard behavior used by Firefox for SVG /// This is nonstandard behavior used by Firefox for SVG
pub fn parse_numbers_are_pixels_non_negative(input: &mut Parser) -> Result<LengthOrPercentage, ()> { pub fn parse_numbers_are_pixels_non_negative(context: &ParserContext,
if let Ok(lop) = input.try(|i| Self::parse_internal(i, AllowedNumericType::NonNegative)) { input: &mut Parser)
-> Result<LengthOrPercentage, ()> {
if let Ok(lop) = input.try(|i| Self::parse_internal(context, i, AllowedNumericType::NonNegative)) {
return Ok(lop) return Ok(lop)
} }
@ -1186,8 +1194,8 @@ impl LengthOrPercentage {
impl Parse for LengthOrPercentage { impl Parse for LengthOrPercentage {
#[inline] #[inline]
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Self::parse_internal(input, AllowedNumericType::All) Self::parse_internal(context, input, AllowedNumericType::All)
} }
} }
@ -1240,19 +1248,21 @@ impl ToCss for LengthOrPercentageOrAuto {
} }
impl LengthOrPercentageOrAuto { impl LengthOrPercentageOrAuto {
fn parse_internal(input: &mut Parser, context: AllowedNumericType) fn parse_internal(context: &ParserContext, input: &mut Parser, num_context: AllowedNumericType)
-> Result<Self, ()> { -> Result<Self, ()> {
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 num_context.is_ok(value.value) =>
NoCalcLength::parse_dimension(value.value, unit).map(LengthOrPercentageOrAuto::Length), NoCalcLength::parse_dimension(context, value.value, unit).map(LengthOrPercentageOrAuto::Length),
Token::Percentage(ref value) if context.is_ok(value.unit_value) => Token::Percentage(ref value) if num_context.is_ok(value.unit_value) =>
Ok(LengthOrPercentageOrAuto::Percentage(Percentage(value.unit_value))), Ok(LengthOrPercentageOrAuto::Percentage(Percentage(value.unit_value))),
Token::Number(ref value) if value.value == 0. => Token::Number(ref value) if value.value == 0. =>
Ok(Self::zero()), Ok(Self::zero()),
Token::Ident(ref value) if value.eq_ignore_ascii_case("auto") => Token::Ident(ref value) if value.eq_ignore_ascii_case("auto") =>
Ok(LengthOrPercentageOrAuto::Auto), Ok(LengthOrPercentageOrAuto::Auto),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = try!(input.parse_nested_block(CalcLengthOrPercentage::parse_length_or_percentage)); let calc = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_length_or_percentage(context, i)
}));
Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc))) Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc)))
}, },
_ => Err(()) _ => Err(())
@ -1261,8 +1271,8 @@ impl LengthOrPercentageOrAuto {
/// Parse a non-negative length, percentage, or auto. /// Parse a non-negative length, percentage, or auto.
#[inline] #[inline]
pub fn parse_non_negative(input: &mut Parser) -> Result<LengthOrPercentageOrAuto, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<LengthOrPercentageOrAuto, ()> {
Self::parse_internal(input, AllowedNumericType::NonNegative) Self::parse_internal(context, input, AllowedNumericType::NonNegative)
} }
/// Returns the `auto` value. /// Returns the `auto` value.
@ -1278,8 +1288,8 @@ impl LengthOrPercentageOrAuto {
impl Parse for LengthOrPercentageOrAuto { impl Parse for LengthOrPercentageOrAuto {
#[inline] #[inline]
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Self::parse_internal(input, AllowedNumericType::All) Self::parse_internal(context, input, AllowedNumericType::All)
} }
} }
@ -1316,18 +1326,20 @@ impl ToCss for LengthOrPercentageOrNone {
} }
} }
impl LengthOrPercentageOrNone { impl LengthOrPercentageOrNone {
fn parse_internal(input: &mut Parser, context: AllowedNumericType) fn parse_internal(context: &ParserContext, input: &mut Parser, num_context: AllowedNumericType)
-> Result<LengthOrPercentageOrNone, ()> -> Result<LengthOrPercentageOrNone, ()>
{ {
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 num_context.is_ok(value.value) =>
NoCalcLength::parse_dimension(value.value, unit).map(LengthOrPercentageOrNone::Length), NoCalcLength::parse_dimension(context, value.value, unit).map(LengthOrPercentageOrNone::Length),
Token::Percentage(ref value) if context.is_ok(value.unit_value) => Token::Percentage(ref value) if num_context.is_ok(value.unit_value) =>
Ok(LengthOrPercentageOrNone::Percentage(Percentage(value.unit_value))), Ok(LengthOrPercentageOrNone::Percentage(Percentage(value.unit_value))),
Token::Number(ref value) if value.value == 0. => Token::Number(ref value) if value.value == 0. =>
Ok(LengthOrPercentageOrNone::Length(NoCalcLength::zero())), Ok(LengthOrPercentageOrNone::Length(NoCalcLength::zero())),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = try!(input.parse_nested_block(CalcLengthOrPercentage::parse_length_or_percentage)); let calc = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_length_or_percentage(context, i)
}));
Ok(LengthOrPercentageOrNone::Calc(Box::new(calc))) Ok(LengthOrPercentageOrNone::Calc(Box::new(calc)))
}, },
Token::Ident(ref value) if value.eq_ignore_ascii_case("none") => Token::Ident(ref value) if value.eq_ignore_ascii_case("none") =>
@ -1337,15 +1349,15 @@ impl LengthOrPercentageOrNone {
} }
/// Parse a non-negative LengthOrPercentageOrNone. /// Parse a non-negative LengthOrPercentageOrNone.
#[inline] #[inline]
pub fn parse_non_negative(input: &mut Parser) -> Result<Self, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Self::parse_internal(input, AllowedNumericType::NonNegative) Self::parse_internal(context, input, AllowedNumericType::NonNegative)
} }
} }
impl Parse for LengthOrPercentageOrNone { impl Parse for LengthOrPercentageOrNone {
#[inline] #[inline]
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
Self::parse_internal(input, AllowedNumericType::All) Self::parse_internal(context, input, AllowedNumericType::All)
} }
} }
@ -1379,12 +1391,13 @@ pub enum LengthOrPercentageOrAutoOrContent {
impl LengthOrPercentageOrAutoOrContent { impl LengthOrPercentageOrAutoOrContent {
/// Parse a non-negative LengthOrPercentageOrAutoOrContent. /// Parse a non-negative LengthOrPercentageOrAutoOrContent.
pub fn parse_non_negative(input: &mut Parser) -> Result<Self, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
let context = AllowedNumericType::NonNegative; let num_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 num_context.is_ok(value.value) =>
NoCalcLength::parse_dimension(value.value, unit).map(LengthOrPercentageOrAutoOrContent::Length), NoCalcLength::parse_dimension(context, value.value, unit)
Token::Percentage(ref value) if context.is_ok(value.unit_value) => .map(LengthOrPercentageOrAutoOrContent::Length),
Token::Percentage(ref value) if num_context.is_ok(value.unit_value) =>
Ok(LengthOrPercentageOrAutoOrContent::Percentage(Percentage(value.unit_value))), Ok(LengthOrPercentageOrAutoOrContent::Percentage(Percentage(value.unit_value))),
Token::Number(ref value) if value.value == 0. => Token::Number(ref value) if value.value == 0. =>
Ok(Self::zero()), Ok(Self::zero()),
@ -1393,7 +1406,9 @@ impl LengthOrPercentageOrAutoOrContent {
Token::Ident(ref value) if value.eq_ignore_ascii_case("content") => Token::Ident(ref value) if value.eq_ignore_ascii_case("content") =>
Ok(LengthOrPercentageOrAutoOrContent::Content), Ok(LengthOrPercentageOrAutoOrContent::Content),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = try!(input.parse_nested_block(CalcLengthOrPercentage::parse_length_or_percentage)); let calc = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_length_or_percentage(context, i)
}));
Ok(LengthOrPercentageOrAutoOrContent::Calc(Box::new(calc))) Ok(LengthOrPercentageOrAutoOrContent::Calc(Box::new(calc)))
}, },
_ => Err(()) _ => Err(())
@ -1438,15 +1453,15 @@ pub type LengthOrNumber = Either<Length, Number>;
impl LengthOrNumber { impl LengthOrNumber {
/// Parse a non-negative LengthOrNumber. /// Parse a non-negative LengthOrNumber.
pub fn parse_non_negative(_: &ParserContext, input: &mut Parser) -> Result<Self, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
// We try to parse as a Number first because, for cases like // We try to parse as a Number first because, for cases like
// LengthOrNumber, we want "0" to be parsed as a plain Number rather // LengthOrNumber, we want "0" to be parsed as a plain Number rather
// than a Length (0px); this matches the behaviour of all major browsers // than a Length (0px); this matches the behaviour of all major browsers
if let Ok(v) = input.try(Number::parse_non_negative) { if let Ok(v) = input.try(|i| Number::parse_non_negative(context, i)) {
return Ok(Either::Second(v)) return Ok(Either::Second(v))
} }
Length::parse_non_negative(input).map(Either::First) Length::parse_non_negative(context, input).map(Either::First)
} }
} }
@ -1485,9 +1500,10 @@ impl ToCss for MinLength {
} }
impl Parse for MinLength { impl Parse for MinLength {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
input.try(ExtremumLength::parse).map(MinLength::ExtremumLength) input.try(ExtremumLength::parse).map(MinLength::ExtremumLength)
.or_else(|()| input.try(LengthOrPercentage::parse_non_negative).map(MinLength::LengthOrPercentage)) .or_else(|()| input.try(|i| LengthOrPercentage::parse_non_negative(context, i))
.map(MinLength::LengthOrPercentage))
.or_else(|()| input.expect_ident_matching("auto").map(|()| MinLength::Auto)) .or_else(|()| input.expect_ident_matching("auto").map(|()| MinLength::Auto))
} }
} }
@ -1525,9 +1541,10 @@ impl ToCss for MaxLength {
} }
impl Parse for MaxLength { impl Parse for MaxLength {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
input.try(ExtremumLength::parse).map(MaxLength::ExtremumLength) input.try(ExtremumLength::parse).map(MaxLength::ExtremumLength)
.or_else(|()| input.try(LengthOrPercentage::parse_non_negative).map(MaxLength::LengthOrPercentage)) .or_else(|()| input.try(|i| LengthOrPercentage::parse_non_negative(context, i))
.map(MaxLength::LengthOrPercentage))
.or_else(|()| { .or_else(|()| {
match_ignore_ascii_case! { &try!(input.expect_ident()), match_ignore_ascii_case! { &try!(input.expect_ident()),
"none" => "none" =>

View file

@ -208,12 +208,12 @@ impl<'a> Mul<CSSFloat> for &'a SimplifiedValueNode {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_integer(input: &mut Parser) -> Result<Integer, ()> { pub fn parse_integer(context: &ParserContext, input: &mut Parser) -> Result<Integer, ()> {
match try!(input.next()) { match try!(input.next()) {
Token::Number(ref value) => value.int_value.ok_or(()).map(Integer::new), Token::Number(ref value) => value.int_value.ok_or(()).map(Integer::new),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let ast = try!(input.parse_nested_block(|i| { let ast = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_sum(i, CalcUnit::Integer) CalcLengthOrPercentage::parse_sum(context, i, CalcUnit::Integer)
})); }));
let mut result = None; let mut result = None;
@ -236,7 +236,7 @@ pub fn parse_integer(input: &mut Parser) -> Result<Integer, ()> {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_number(input: &mut Parser) -> Result<Number, ()> { pub fn parse_number(context: &ParserContext, input: &mut Parser) -> Result<Number, ()> {
match try!(input.next()) { match try!(input.next()) {
Token::Number(ref value) => { Token::Number(ref value) => {
Ok(Number { Ok(Number {
@ -245,7 +245,9 @@ pub fn parse_number(input: &mut Parser) -> Result<Number, ()> {
}) })
}, },
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let ast = try!(input.parse_nested_block(|i| CalcLengthOrPercentage::parse_sum(i, CalcUnit::Number))); let ast = try!(input.parse_nested_block(|i| {
CalcLengthOrPercentage::parse_sum(context, i, CalcUnit::Number)
}));
let mut result = None; let mut result = None;
@ -298,9 +300,9 @@ impl BorderRadiusSize {
impl Parse for BorderRadiusSize { impl Parse for BorderRadiusSize {
#[inline] #[inline]
fn parse(_context: &ParserContext, 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(context, input));
let second = input.try(LengthOrPercentage::parse_non_negative) let second = input.try(|i| LengthOrPercentage::parse_non_negative(context, i))
.unwrap_or_else(|()| first.clone()); .unwrap_or_else(|()| first.clone());
Ok(BorderRadiusSize(Size2D::new(first, second))) Ok(BorderRadiusSize(Size2D::new(first, second)))
} }
@ -428,11 +430,11 @@ impl Angle {
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(_context: &ParserContext, 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::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(CalcLengthOrPercentage::parse_angle) input.parse_nested_block(|i| CalcLengthOrPercentage::parse_angle(context, i))
}, },
_ => Err(()) _ => Err(())
} }
@ -457,12 +459,12 @@ impl Angle {
/// unitless 0 angle and stores it as '0deg'. We can remove this and /// unitless 0 angle and stores it as '0deg'. We can remove this and
/// get back to the unified version Angle::parse once /// get back to the unified version Angle::parse once
/// https://github.com/w3c/csswg-drafts/issues/1162 is resolved. /// https://github.com/w3c/csswg-drafts/issues/1162 is resolved.
pub fn parse_with_unitless(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { pub fn parse_with_unitless(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::zero()), Token::Number(ref value) if value.value == 0. => Ok(Angle::zero()),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => { Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(CalcLengthOrPercentage::parse_angle) input.parse_nested_block(|i| CalcLengthOrPercentage::parse_angle(context, i))
}, },
_ => Err(()) _ => Err(())
} }
@ -485,8 +487,8 @@ pub fn parse_border_radius(context: &ParserContext, input: &mut Parser) -> Resul
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_border_width(input: &mut Parser) -> Result<Length, ()> { pub fn parse_border_width(context: &ParserContext, input: &mut Parser) -> Result<Length, ()> {
input.try(Length::parse_non_negative).or_else(|()| { input.try(|i| Length::parse_non_negative(context, i)).or_else(|()| {
match_ignore_ascii_case! { &try!(input.expect_ident()), match_ignore_ascii_case! { &try!(input.expect_ident()),
"thin" => Ok(Length::from_px(1.)), "thin" => Ok(Length::from_px(1.)),
"medium" => Ok(Length::from_px(3.)), "medium" => Ok(Length::from_px(3.)),
@ -507,8 +509,8 @@ pub enum BorderWidth {
} }
impl Parse for BorderWidth { impl Parse for BorderWidth {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<BorderWidth, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<BorderWidth, ()> {
match input.try(Length::parse_non_negative) { match input.try(|i| Length::parse_non_negative(context, i)) {
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()),
"thin" => Ok(BorderWidth::Thin), "thin" => Ok(BorderWidth::Thin),
@ -659,13 +661,13 @@ impl ToComputedValue for Time {
} }
impl Parse for Time { impl Parse for Time {
fn parse(_context: &ParserContext, 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)
} }
Ok(Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => { Ok(Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(CalcLengthOrPercentage::parse_time) input.parse_nested_block(|i| CalcLengthOrPercentage::parse_time(context, i))
} }
_ => Err(()) _ => Err(())
} }
@ -700,14 +702,14 @@ pub struct Number {
no_viewport_percentage!(Number); no_viewport_percentage!(Number);
impl Parse for Number { impl Parse for Number {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
parse_number(input) parse_number(context, input)
} }
} }
impl Number { impl Number {
fn parse_with_minimum(input: &mut Parser, min: CSSFloat) -> Result<Number, ()> { fn parse_with_minimum(context: &ParserContext, input: &mut Parser, min: CSSFloat) -> Result<Number, ()> {
match parse_number(input) { match parse_number(context, input) {
Ok(value) if value.value >= min => Ok(value), Ok(value) if value.value >= min => Ok(value),
_ => Err(()), _ => Err(()),
} }
@ -722,13 +724,13 @@ impl Number {
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_non_negative(input: &mut Parser) -> Result<Number, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Number, ()> {
Number::parse_with_minimum(input, 0.0) Number::parse_with_minimum(context, input, 0.0)
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_at_least_one(input: &mut Parser) -> Result<Number, ()> { pub fn parse_at_least_one(context: &ParserContext, input: &mut Parser) -> Result<Number, ()> {
Number::parse_with_minimum(input, 1.0) Number::parse_with_minimum(context, input, 1.0)
} }
} }
@ -775,12 +777,12 @@ pub enum NumberOrPercentage {
no_viewport_percentage!(NumberOrPercentage); no_viewport_percentage!(NumberOrPercentage);
impl Parse for NumberOrPercentage { impl Parse for NumberOrPercentage {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
if let Ok(per) = input.try(Percentage::parse_non_negative) { if let Ok(per) = input.try(Percentage::parse_non_negative) {
return Ok(NumberOrPercentage::Percentage(per)); return Ok(NumberOrPercentage::Percentage(per));
} }
Number::parse_non_negative(input).map(NumberOrPercentage::Number) Number::parse_non_negative(context, input).map(NumberOrPercentage::Number)
} }
} }
@ -801,8 +803,8 @@ pub struct Opacity(Number);
no_viewport_percentage!(Opacity); no_viewport_percentage!(Opacity);
impl Parse for Opacity { impl Parse for Opacity {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
parse_number(input).map(Opacity) parse_number(context, input).map(Opacity)
} }
} }
@ -860,27 +862,27 @@ impl Integer {
no_viewport_percentage!(Integer); no_viewport_percentage!(Integer);
impl Parse for Integer { impl Parse for Integer {
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
parse_integer(input) parse_integer(context, input)
} }
} }
impl Integer { impl Integer {
fn parse_with_minimum(input: &mut Parser, min: i32) -> Result<Integer, ()> { fn parse_with_minimum(context: &ParserContext, input: &mut Parser, min: i32) -> Result<Integer, ()> {
match parse_integer(input) { match parse_integer(context, input) {
Ok(value) if value.value() >= min => Ok(value), Ok(value) if value.value() >= min => Ok(value),
_ => Err(()), _ => Err(()),
} }
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_non_negative(input: &mut Parser) -> Result<Integer, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Integer, ()> {
Integer::parse_with_minimum(input, 0) Integer::parse_with_minimum(context, input, 0)
} }
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse_positive(input: &mut Parser) -> Result<Integer, ()> { pub fn parse_positive(context: &ParserContext, input: &mut Parser) -> Result<Integer, ()> {
Integer::parse_with_minimum(input, 1) Integer::parse_with_minimum(context, input, 1)
} }
} }
@ -990,7 +992,7 @@ impl ToComputedValue for Shadow {
impl Shadow { impl Shadow {
// disable_spread_and_inset is for filter: drop-shadow(...) // disable_spread_and_inset is for filter: drop-shadow(...)
#[allow(missing_docs)] #[allow(missing_docs)]
pub fn parse(context: &ParserContext, input: &mut Parser, disable_spread_and_inset: bool) -> Result<Shadow, ()> { pub fn parse(context: &ParserContext, input: &mut Parser, disable_spread_and_inset: bool) -> Result<Shadow, ()> {
let mut lengths = [Length::zero(), Length::zero(), Length::zero(), Length::zero()]; let mut lengths = [Length::zero(), Length::zero(), Length::zero(), Length::zero()];
let mut lengths_parsed = false; let mut lengths_parsed = false;
let mut color = None; let mut color = None;
@ -1007,7 +1009,7 @@ impl Shadow {
if let Ok(value) = input.try(|i| Length::parse(context, i)) { if let Ok(value) = input.try(|i| Length::parse(context, i)) {
lengths[0] = value; lengths[0] = value;
lengths[1] = try!(Length::parse(context, input)); lengths[1] = try!(Length::parse(context, input));
if let Ok(value) = input.try(|i| Length::parse_non_negative(i)) { if let Ok(value) = input.try(|i| Length::parse_non_negative(context, i)) {
lengths[2] = value; lengths[2] = value;
if !disable_spread_and_inset { if !disable_spread_and_inset {
if let Ok(value) = input.try(|i| Length::parse(context, i)) { if let Ok(value) = input.try(|i| Length::parse(context, i)) {
@ -1204,14 +1206,14 @@ pub type LengthOrPercentageOrNumber = Either<LengthOrPercentage, Number>;
impl LengthOrPercentageOrNumber { impl LengthOrPercentageOrNumber {
/// parse a <length-percentage> | <number> enforcing that the contents aren't negative /// parse a <length-percentage> | <number> enforcing that the contents aren't negative
pub fn parse_non_negative(_: &ParserContext, input: &mut Parser) -> Result<Self, ()> { pub fn parse_non_negative(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
// NB: Parse numbers before Lengths so we are consistent about how to // NB: Parse numbers before Lengths so we are consistent about how to
// recognize and serialize "0". // recognize and serialize "0".
if let Ok(num) = input.try(Number::parse_non_negative) { if let Ok(num) = input.try(|i| Number::parse_non_negative(context, i)) {
return Ok(Either::Second(num)) return Ok(Either::Second(num))
} }
LengthOrPercentage::parse_non_negative(input).map(Either::First) LengthOrPercentage::parse_non_negative(context, input).map(Either::First)
} }
} }

View file

@ -166,10 +166,10 @@ impl FromMeta for ViewportLength {
} }
impl ViewportLength { impl ViewportLength {
fn parse(input: &mut Parser) -> Result<Self, ()> { fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ()> {
// we explicitly do not accept 'extend-to-zoom', since it is a UA // we explicitly do not accept 'extend-to-zoom', since it is a UA
// internal value for <META> viewport translation // internal value for <META> viewport translation
LengthOrPercentageOrAuto::parse_non_negative(input).map(ViewportLength::Specified) LengthOrPercentageOrAuto::parse_non_negative(context, input).map(ViewportLength::Specified)
} }
} }
@ -245,9 +245,9 @@ impl ToCss for ViewportDescriptorDeclaration {
} }
} }
fn parse_shorthand(input: &mut Parser) -> Result<(ViewportLength, ViewportLength), ()> { fn parse_shorthand(context: &ParserContext, input: &mut Parser) -> Result<(ViewportLength, ViewportLength), ()> {
let min = try!(ViewportLength::parse(input)); let min = try!(ViewportLength::parse(context, input));
match input.try(ViewportLength::parse) { match input.try(|i| ViewportLength::parse(context, i)) {
Err(()) => Ok((min.clone(), min)), Err(()) => Ok((min.clone(), min)),
Ok(max) => Ok((min, max)) Ok(max) => Ok((min, max))
} }
@ -263,7 +263,7 @@ impl<'a, 'b> DeclarationParser for ViewportRuleParser<'a, 'b> {
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<ViewportDescriptorDeclaration>, ()> { fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<Vec<ViewportDescriptorDeclaration>, ()> {
macro_rules! declaration { macro_rules! declaration {
($declaration:ident($parse:path)) => { ($declaration:ident($parse:expr)) => {
declaration!($declaration(value: try!($parse(input)), declaration!($declaration(value: try!($parse(input)),
important: input.try(parse_important).is_ok())) important: input.try(parse_important).is_ok()))
}; };
@ -276,11 +276,11 @@ impl<'a, 'b> DeclarationParser for ViewportRuleParser<'a, 'b> {
} }
macro_rules! ok { macro_rules! ok {
($declaration:ident($parse:path)) => { ($declaration:ident($parse:expr)) => {
Ok(vec![declaration!($declaration($parse))]) Ok(vec![declaration!($declaration($parse))])
}; };
(shorthand -> [$min:ident, $max:ident]) => {{ (shorthand -> [$min:ident, $max:ident]) => {{
let shorthand = try!(parse_shorthand(input)); let shorthand = try!(parse_shorthand(self.context, input));
let important = input.try(parse_important).is_ok(); let important = input.try(parse_important).is_ok();
Ok(vec![declaration!($min(value: shorthand.0, important: important)), Ok(vec![declaration!($min(value: shorthand.0, important: important)),
@ -289,11 +289,11 @@ impl<'a, 'b> DeclarationParser for ViewportRuleParser<'a, 'b> {
} }
match_ignore_ascii_case! { name, match_ignore_ascii_case! { name,
"min-width" => ok!(MinWidth(ViewportLength::parse)), "min-width" => ok!(MinWidth(|i| ViewportLength::parse(self.context, i))),
"max-width" => ok!(MaxWidth(ViewportLength::parse)), "max-width" => ok!(MaxWidth(|i| ViewportLength::parse(self.context, i))),
"width" => ok!(shorthand -> [MinWidth, MaxWidth]), "width" => ok!(shorthand -> [MinWidth, MaxWidth]),
"min-height" => ok!(MinHeight(ViewportLength::parse)), "min-height" => ok!(MinHeight(|i| ViewportLength::parse(self.context, i))),
"max-height" => ok!(MaxHeight(ViewportLength::parse)), "max-height" => ok!(MaxHeight(|i| ViewportLength::parse(self.context, i))),
"height" => ok!(shorthand -> [MinHeight, MaxHeight]), "height" => ok!(shorthand -> [MinHeight, MaxHeight]),
"zoom" => ok!(Zoom(Zoom::parse)), "zoom" => ok!(Zoom(Zoom::parse)),
"min-zoom" => ok!(MinZoom(Zoom::parse)), "min-zoom" => ok!(MinZoom(Zoom::parse)),

View file

@ -1166,8 +1166,11 @@ pub extern "C" fn Servo_MediaList_GetText(list: RawServoMediaListBorrowed, resul
pub extern "C" fn Servo_MediaList_SetText(list: RawServoMediaListBorrowed, text: *const nsACString) { pub extern "C" fn Servo_MediaList_SetText(list: RawServoMediaListBorrowed, text: *const nsACString) {
let text = unsafe { text.as_ref().unwrap().as_str_unchecked() }; let text = unsafe { text.as_ref().unwrap().as_str_unchecked() };
let mut parser = Parser::new(&text); let mut parser = Parser::new(&text);
write_locked_arc(list, |list: &mut MediaList| { let url_data = unsafe { dummy_url_data() };
*list = parse_media_query_list(&mut parser); let reporter = StdoutErrorReporter;
let context = ParserContext::new_for_cssom(url_data, &reporter, Some(CssRuleType::Media));
write_locked_arc(list, |list: &mut MediaList| {
*list = parse_media_query_list(&context, &mut parser);
}) })
} }
@ -1193,8 +1196,11 @@ pub extern "C" fn Servo_MediaList_GetMediumAt(list: RawServoMediaListBorrowed, i
pub extern "C" fn Servo_MediaList_AppendMedium(list: RawServoMediaListBorrowed, pub extern "C" fn Servo_MediaList_AppendMedium(list: RawServoMediaListBorrowed,
new_medium: *const nsACString) { new_medium: *const nsACString) {
let new_medium = unsafe { new_medium.as_ref().unwrap().as_str_unchecked() }; let new_medium = unsafe { new_medium.as_ref().unwrap().as_str_unchecked() };
let url_data = unsafe { dummy_url_data() };
let reporter = StdoutErrorReporter;
let context = ParserContext::new_for_cssom(url_data, &reporter, Some(CssRuleType::Media));
write_locked_arc(list, |list: &mut MediaList| { write_locked_arc(list, |list: &mut MediaList| {
list.append_medium(new_medium); list.append_medium(&context, new_medium);
}) })
} }
@ -1202,7 +1208,10 @@ pub extern "C" fn Servo_MediaList_AppendMedium(list: RawServoMediaListBorrowed,
pub extern "C" fn Servo_MediaList_DeleteMedium(list: RawServoMediaListBorrowed, pub extern "C" fn Servo_MediaList_DeleteMedium(list: RawServoMediaListBorrowed,
old_medium: *const nsACString) -> bool { old_medium: *const nsACString) -> bool {
let old_medium = unsafe { old_medium.as_ref().unwrap().as_str_unchecked() }; let old_medium = unsafe { old_medium.as_ref().unwrap().as_str_unchecked() };
write_locked_arc(list, |list: &mut MediaList| list.delete_medium(old_medium)) let url_data = unsafe { dummy_url_data() };
let reporter = StdoutErrorReporter;
let context = ParserContext::new_for_cssom(url_data, &reporter, Some(CssRuleType::Media));
write_locked_arc(list, |list: &mut MediaList| list.delete_medium(&context, old_medium))
} }
macro_rules! get_longhand_from_id { macro_rules! get_longhand_from_id {

View file

@ -4,6 +4,9 @@
use app_units::Au; use app_units::Au;
use cssparser::Parser; use cssparser::Parser;
use media_queries::CSSErrorReporterTest;
use style::parser::ParserContext;
use style::stylesheets::{CssRuleType, Origin};
use style::values::HasViewportPercentage; use style::values::HasViewportPercentage;
use style::values::specified::{AbsoluteLength, ViewportPercentageLength, NoCalcLength}; use style::values::specified::{AbsoluteLength, ViewportPercentageLength, NoCalcLength};
use style::values::specified::length::{CalcLengthOrPercentage, CalcUnit}; use style::values::specified::length::{CalcLengthOrPercentage, CalcUnit};
@ -19,8 +22,11 @@ fn length_has_viewport_percentage() {
#[test] #[test]
fn calc_top_level_number_with_unit() { fn calc_top_level_number_with_unit() {
fn parse(text: &str, unit: CalcUnit) -> Result<CalcLengthOrPercentage, ()> { fn parse(text: &str, unit: CalcUnit) -> Result<CalcLengthOrPercentage, ()> {
let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap();
let reporter = CSSErrorReporterTest;
let context = ParserContext::new(Origin::Author, &url, &reporter, Some(CssRuleType::Style));
let mut parser = Parser::new(text); let mut parser = Parser::new(text);
CalcLengthOrPercentage::parse(&mut parser, unit) CalcLengthOrPercentage::parse(&context, &mut parser, unit)
} }
assert_eq!(parse("1", CalcUnit::Length), Err(())); assert_eq!(parse("1", CalcUnit::Length), Err(()));
assert_eq!(parse("1", CalcUnit::LengthOrPercentage), Err(())); assert_eq!(parse("1", CalcUnit::LengthOrPercentage), Err(()));