Update cssparser to 0.18

https://github.com/servo/rust-cssparser/pull/171
This commit is contained in:
Simon Sapin 2017-07-20 21:03:53 +02:00
parent 30d6d6024b
commit eb98ae6e04
64 changed files with 541 additions and 512 deletions

View file

@ -38,7 +38,7 @@ bitflags = "0.7"
bit-vec = "0.4.3"
byteorder = "1.0"
cfg-if = "0.1.0"
cssparser = "0.17.0"
cssparser = "0.18"
encoding = {version = "0.2", optional = true}
euclid = "0.15"
fnv = "1.0"

View file

@ -8,7 +8,7 @@
use Atom;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser};
use cssparser::{Parser, Token, serialize_identifier, BasicParseError, CompactCowStr};
use cssparser::{Parser, Token, serialize_identifier, BasicParseError, CowRcStr};
use error_reporting::ContextualParseError;
#[cfg(feature = "gecko")] use gecko::rules::CounterStyleDescriptors;
#[cfg(feature = "gecko")] use gecko_bindings::structs::nsCSSCounterDesc;
@ -184,7 +184,7 @@ macro_rules! counter_style_descriptors {
type Declaration = ();
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<(), ParseError<'i>> {
match_ignore_ascii_case! { &*name,
$(
@ -295,7 +295,7 @@ pub enum System {
impl Parse for System {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input.expect_ident()?,
try_match_ident_ignore_ascii_case! { input.expect_ident_cloned()?,
"cyclic" => Ok(System::Cyclic),
"numeric" => Ok(System::Numeric),
"alphabetic" => Ok(System::Alphabetic),
@ -351,9 +351,9 @@ pub enum Symbol {
impl Parse for Symbol {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
match input.next() {
Ok(Token::QuotedString(s)) => Ok(Symbol::String(s.into_owned())),
Ok(Token::Ident(s)) => Ok(Symbol::Ident(s.into_owned())),
Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::QuotedString(ref s)) => Ok(Symbol::String(s.as_ref().to_owned())),
Ok(&Token::Ident(ref s)) => Ok(Symbol::Ident(s.as_ref().to_owned())),
Ok(t) => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => Err(e.into()),
}
}
@ -419,9 +419,9 @@ impl Parse for Ranges {
fn parse_bound<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Option<i32>, ParseError<'i>> {
match input.next() {
Ok(Token::Number { int_value: Some(v), .. }) => Ok(Some(v)),
Ok(Token::Ident(ref ident)) if ident.eq_ignore_ascii_case("infinite") => Ok(None),
Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::Number { int_value: Some(v), .. }) => Ok(Some(v)),
Ok(&Token::Ident(ref ident)) if ident.eq_ignore_ascii_case("infinite") => Ok(None),
Ok(t) => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => Err(e.into()),
}
}

View file

@ -252,7 +252,8 @@ fn parse_declaration_value_block<'i, 't>
ParseError<'i>> {
let mut token_start = input.position();
let mut token = match input.next_including_whitespace_and_comments() {
Ok(token) => token,
// FIXME: remove clone() when borrows are non-lexical
Ok(token) => token.clone(),
Err(_) => return Ok((TokenSerializationType::nothing(), TokenSerializationType::nothing()))
};
let first_token_type = token.serialization_type();
@ -351,7 +352,8 @@ fn parse_declaration_value_block<'i, 't>
token_start = input.position();
token = match input.next_including_whitespace_and_comments() {
Ok(token) => token,
// FIXME: remove clone() when borrows are non-lexical
Ok(token) => token.clone(),
Err(..) => return Ok((first_token_type, last_token_type)),
};
}
@ -361,7 +363,7 @@ fn parse_declaration_value_block<'i, 't>
fn parse_var_function<'i, 't>(input: &mut Parser<'i, 't>,
references: &mut Option<HashSet<Name>>)
-> Result<(), ParseError<'i>> {
let name = input.expect_ident()?;
let name = input.expect_ident_cloned()?;
let name: Result<_, ParseError> =
parse_name(&name)
.map_err(|()| SelectorParseError::UnexpectedIdent(name.clone()).into());
@ -597,7 +599,8 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
let mut set_position_at_next_iteration = false;
loop {
let before_this_token = input.position();
let next = input.next_including_whitespace_and_comments();
// FIXME: remove clone() when borrows are non-lexical
let next = input.next_including_whitespace_and_comments().map(|t| t.clone());
if set_position_at_next_iteration {
*position = (before_this_token, match next {
Ok(ref token) => token.serialization_type(),
@ -615,7 +618,7 @@ fn substitute_block<'i, 't, F>(input: &mut Parser<'i, 't>,
input.slice(position.0..before_this_token), position.1, last_token_type);
input.parse_nested_block(|input| {
// parse_var_function() ensures neither .unwrap() will fail.
let name = input.expect_ident().unwrap();
let name = input.expect_ident_cloned().unwrap();
let name = Atom::from(parse_name(&name).unwrap());
if let Ok(last) = substitute_one(&name, partial_computed_value) {

View file

@ -12,7 +12,7 @@
use computed_values::{font_feature_settings, font_stretch, font_style, font_weight};
use computed_values::font_family::FamilyName;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser};
use cssparser::{SourceLocation, CompactCowStr};
use cssparser::{SourceLocation, CowRcStr};
use error_reporting::ContextualParseError;
#[cfg(feature = "gecko")] use gecko_bindings::structs::CSSFontFaceDescriptors;
#[cfg(feature = "gecko")] use cssparser::UnicodeRange;
@ -197,7 +197,7 @@ impl Parse for Source {
let format_hints = if input.try(|input| input.expect_function_matching("format")).is_ok() {
input.parse_nested_block(|input| {
input.parse_comma_separated(|input| {
Ok(input.expect_string()?.into_owned())
Ok(input.expect_string()?.as_ref().to_owned())
})
})?
} else {
@ -275,7 +275,7 @@ macro_rules! font_face_descriptors_common {
type Declaration = ();
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<(), ParseError<'i>> {
match_ignore_ascii_case! { &*name,
$(

View file

@ -240,11 +240,11 @@ impl Resolution {
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let (value, unit) = match input.next()? {
Token::Dimension { value, unit, .. } => {
let (value, unit) = match *input.next()? {
Token::Dimension { value, ref unit, .. } => {
(value, unit)
},
t => return Err(BasicParseError::UnexpectedToken(t).into()),
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
};
if value <= 0. {
@ -256,7 +256,7 @@ impl Resolution {
"dppx" => Ok(Resolution::Dppx(value)),
"dpcm" => Ok(Resolution::Dpcm(value)),
_ => Err(())
}).map_err(|()| StyleParseError::UnexpectedDimension(unit).into())
}).map_err(|()| StyleParseError::UnexpectedDimension(unit.clone()).into())
}
}
@ -474,47 +474,55 @@ impl Expression {
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let ident = input.expect_ident()?;
// FIXME: remove extra indented block when lifetimes are non-lexical
let feature;
let range;
{
let ident = input.expect_ident()?;
let mut flags = 0;
let result = {
let mut feature_name = &*ident;
let mut flags = 0;
let result = {
let mut feature_name = &**ident;
// TODO(emilio): this is under a pref in Gecko.
if starts_with_ignore_ascii_case(feature_name, "-webkit-") {
feature_name = &feature_name[8..];
flags |= nsMediaFeature_RequirementFlags::eHasWebkitPrefix as u8;
}
// TODO(emilio): this is under a pref in Gecko.
if starts_with_ignore_ascii_case(feature_name, "-webkit-") {
feature_name = &feature_name[8..];
flags |= nsMediaFeature_RequirementFlags::eHasWebkitPrefix as u8;
}
let range = if starts_with_ignore_ascii_case(feature_name, "min-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMin
} else if starts_with_ignore_ascii_case(feature_name, "max-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMax
} else {
nsMediaExpression_Range::eEqual
let range = if starts_with_ignore_ascii_case(feature_name, "min-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMin
} else if starts_with_ignore_ascii_case(feature_name, "max-") {
feature_name = &feature_name[4..];
nsMediaExpression_Range::eMax
} else {
nsMediaExpression_Range::eEqual
};
let atom = Atom::from(feature_name);
match find_feature(|f| atom.as_ptr() == unsafe { *f.mName }) {
Some(f) => Ok((f, range)),
None => Err(()),
}
};
let atom = Atom::from(feature_name);
match find_feature(|f| atom.as_ptr() == unsafe { *f.mName }) {
Some(f) => Ok((f, range)),
None => Err(()),
match result {
Ok((f, r)) => {
feature = f;
range = r;
}
Err(()) => return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into()),
}
};
let (feature, range) = match result {
Ok((feature, range)) => (feature, range),
Err(()) => return Err(SelectorParseError::UnexpectedIdent(ident).into()),
};
if (feature.mReqFlags & !flags) != 0 {
return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into());
}
if (feature.mReqFlags & !flags) != 0 {
return Err(SelectorParseError::UnexpectedIdent(ident).into());
}
if range != nsMediaExpression_Range::eEqual &&
feature.mRangeType != nsMediaFeature_RangeType::eMinMaxAllowed {
return Err(SelectorParseError::UnexpectedIdent(ident).into());
if range != nsMediaExpression_Range::eEqual &&
feature.mRangeType != nsMediaFeature_RangeType::eMinMaxAllowed {
return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into());
}
}
// If there's no colon, this is a media query of the form
@ -590,7 +598,7 @@ impl Expression {
MediaExpressionValue::Enumerated(value)
}
nsMediaFeature_ValueType::eIdent => {
MediaExpressionValue::Ident(input.expect_ident()?.into_owned())
MediaExpressionValue::Ident(input.expect_ident()?.as_ref().to_owned())
}
};

View file

@ -4,7 +4,7 @@
//! Gecko-specific bits for selector-parsing.
use cssparser::{BasicParseError, Parser, ToCss, Token, CompactCowStr};
use cssparser::{BasicParseError, Parser, ToCss, Token, CowRcStr};
use element_state::ElementState;
use gecko_bindings::structs::CSSPseudoClassType;
use selector_parser::{SelectorParser, PseudoElementCascadeType};
@ -267,12 +267,12 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
type Impl = SelectorImpl;
type Error = StyleParseError<'i>;
fn is_pseudo_element_allows_single_colon(name: &CompactCowStr<'i>) -> bool {
fn is_pseudo_element_allows_single_colon(name: &CowRcStr<'i>) -> bool {
::selectors::parser::is_css2_pseudo_element(name) ||
name.starts_with("-moz-tree-") // tree pseudo-elements
}
fn parse_non_ts_pseudo_class(&self, name: CompactCowStr<'i>)
fn parse_non_ts_pseudo_class(&self, name: CowRcStr<'i>)
-> Result<NonTSPseudoClass, ParseError<'i>> {
macro_rules! pseudo_class_parse {
(bare: [$(($css:expr, $name:ident, $gecko_type:tt, $state:tt, $flags:tt),)*],
@ -294,7 +294,7 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
}
fn parse_non_ts_functional_pseudo_class<'t>(&self,
name: CompactCowStr<'i>,
name: CowRcStr<'i>,
parser: &mut Parser<'i, 't>)
-> Result<NonTSPseudoClass, ParseError<'i>> {
macro_rules! pseudo_class_string_parse {
@ -338,12 +338,12 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
}
}
fn parse_pseudo_element(&self, name: CompactCowStr<'i>) -> Result<PseudoElement, ParseError<'i>> {
fn parse_pseudo_element(&self, name: CowRcStr<'i>) -> Result<PseudoElement, ParseError<'i>> {
PseudoElement::from_slice(&name, self.in_user_agent_stylesheet())
.ok_or(SelectorParseError::UnexpectedIdent(name.clone()).into())
}
fn parse_functional_pseudo_element<'t>(&self, name: CompactCowStr<'i>,
fn parse_functional_pseudo_element<'t>(&self, name: CowRcStr<'i>,
parser: &mut Parser<'i, 't>)
-> Result<PseudoElement, ParseError<'i>> {
if name.starts_with("-moz-tree-") {
@ -352,9 +352,9 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
let mut args = Vec::new();
loop {
match parser.next() {
Ok(Token::Ident(ident)) => args.push(ident.into_owned()),
Ok(Token::Comma) => {},
Ok(t) => return Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::Ident(ref ident)) => args.push(ident.as_ref().to_owned()),
Ok(&Token::Comma) => {},
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(BasicParseError::EndOfInput) => break,
_ => unreachable!("Parser::next() shouldn't return any other error"),
}

View file

@ -6,7 +6,7 @@
use gecko_bindings::structs::nsIAtom;
use precomputed_hash::PrecomputedHash;
use std::borrow::{Borrow, Cow};
use std::borrow::Borrow;
use std::fmt;
use std::ops::Deref;
use string_cache::{Atom, WeakAtom};
@ -54,8 +54,8 @@ impl Deref for Namespace {
}
}
impl<'a> From<Cow<'a, str>> for Namespace {
fn from(s: Cow<'a, str>) -> Self {
impl<'a> From<&'a str> for Namespace {
fn from(s: &'a str) -> Self {
Namespace(Atom::from(s))
}
}

View file

@ -17,7 +17,7 @@ macro_rules! try_match_ident_ignore_ascii_case {
_ => Err(()),
})
.map_err(|()| {
::selectors::parser::SelectorParseError::UnexpectedIdent(__ident).into()
::selectors::parser::SelectorParseError::UnexpectedIdent(__ident.clone()).into()
})
}
}

View file

@ -211,10 +211,10 @@ impl MediaQuery {
None
};
let media_type = match input.try(|input| input.expect_ident()) {
let media_type = match input.try(|i| i.expect_ident_cloned()) {
Ok(ident) => {
let result: Result<_, ParseError> = MediaQueryType::parse(&*ident)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident).into());
.map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into());
result?
}
Err(_) => {
@ -263,7 +263,7 @@ pub fn parse_media_query_list(context: &ParserContext, input: &mut Parser) -> Me
}
match input.next() {
Ok(Token::Comma) => {},
Ok(&Token::Comma) => {},
Ok(_) => unreachable!(),
Err(_) => break,
}

View file

@ -7,7 +7,7 @@
#![deny(missing_docs)]
use context::QuirksMode;
use cssparser::{DeclarationListParser, parse_important, ParserInput, CompactCowStr};
use cssparser::{DeclarationListParser, parse_important, ParserInput, CowRcStr};
use cssparser::{Parser, AtRuleParser, DeclarationParser, Delimiter, ParseError as CssParseError};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use parser::{ParserContext, log_css_error};
@ -945,7 +945,7 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for PropertyDeclarationParser<'a, 'b> {
type Declaration = Importance;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<Importance, ParseError<'i>> {
let id = match PropertyId::parse(&name) {
Ok(id) => id,

View file

@ -2808,7 +2808,7 @@ fn static_assert() {
if atom.is_empty() {
AnimationName(None)
} else {
AnimationName(Some(KeyframesName::from_ident(atom.to_string())))
AnimationName(Some(KeyframesName::from_ident(&atom.to_string())))
}
}
pub fn copy_animation_name_from(&mut self, other: &Self) {

View file

@ -286,7 +286,7 @@ impl TransitionProperty {
match supported {
Ok(Some(property)) => Ok(property),
Ok(None) => CustomIdent::from_ident(ident, &[]).map(TransitionProperty::Unsupported),
Err(()) => Err(SelectorParseError::UnexpectedIdent(ident).into()),
Err(()) => Err(SelectorParseError::UnexpectedIdent(ident.clone()).into()),
}
}

View file

@ -122,14 +122,14 @@ ${helpers.predefined_type("background-image", "ImageLayer",
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let ident = input.expect_ident()?;
let ident = input.expect_ident_cloned()?;
(match_ignore_ascii_case! { &ident,
"repeat-x" => Ok(SpecifiedValue::RepeatX),
"repeat-y" => Ok(SpecifiedValue::RepeatY),
_ => Err(()),
}).or_else(|()| {
let horizontal: Result<_, ParseError> = RepeatKeyword::from_ident(&ident)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident).into());
.map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into());
let horizontal = horizontal?;
let vertical = input.try(RepeatKeyword::parse).ok();
Ok(SpecifiedValue::Other(horizontal, vertical))

View file

@ -1025,7 +1025,7 @@ ${helpers.predefined_type(
}
Ok(SpecifiedValue(Space::parse(input, |input| {
let function = input.expect_function()?;
let function = input.expect_function()?.clone();
input.parse_nested_block(|input| {
let result = match_ignore_ascii_case! { &function,
"matrix" => {
@ -1217,7 +1217,7 @@ ${helpers.predefined_type(
_ => Err(()),
};
result
.map_err(|()| StyleParseError::UnexpectedFunction(function).into())
.map_err(|()| StyleParseError::UnexpectedFunction(function.clone()).into())
})
})?))
}
@ -1764,7 +1764,7 @@ ${helpers.predefined_type("transform-origin",
return Ok(result)
}
while let Ok(name) = input.try(|input| input.expect_ident()) {
while let Ok(name) = input.try(|i| i.expect_ident_cloned()) {
let flag = match_ignore_ascii_case! { &name,
"layout" => Some(LAYOUT),
"style" => Some(STYLE),
@ -1773,7 +1773,7 @@ ${helpers.predefined_type("transform-origin",
};
let flag = match flag {
Some(flag) if !result.contains(flag) => flag,
_ => return Err(SelectorParseError::UnexpectedIdent(name).into())
_ => return Err(SelectorParseError::UnexpectedIdent(name.clone()).into())
};
result.insert(flag);
}
@ -1960,7 +1960,8 @@ ${helpers.predefined_type("shape-outside", "basic_shape::FloatAreaShape",
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input.expect_ident()?,
// FIXME: remove clone() when lifetimes are non-lexical
try_match_ident_ignore_ascii_case! { input.expect_ident()?.clone(),
"auto" => Ok(TOUCH_ACTION_AUTO),
"none" => Ok(TOUCH_ACTION_NONE),
"manipulation" => Ok(TOUCH_ACTION_MANIPULATION),

View file

@ -134,7 +134,7 @@
if let Some(color) = color_name(&ident) {
Ok(*color)
} else {
Err(SelectorParseError::UnexpectedIdent(ident).into())
Err(SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
}
}

View file

@ -179,21 +179,22 @@
continue;
}
% endif
match input.next() {
Ok(Token::QuotedString(value)) => {
content.push(ContentItem::String(value.into_owned()))
// FIXME: remove clone() when lifetimes are non-lexical
match input.next().map(|t| t.clone()) {
Ok(Token::QuotedString(ref value)) => {
content.push(ContentItem::String(value.as_ref().to_owned()))
}
Ok(Token::Function(name)) => {
Ok(Token::Function(ref name)) => {
let result = match_ignore_ascii_case! { &name,
"counter" => Some(input.parse_nested_block(|input| {
let name = input.expect_ident()?.into_owned();
let name = input.expect_ident()?.as_ref().to_owned();
let style = parse_counter_style(context, input);
Ok(ContentItem::Counter(name, style))
})),
"counters" => Some(input.parse_nested_block(|input| {
let name = input.expect_ident()?.into_owned();
let name = input.expect_ident()?.as_ref().to_owned();
input.expect_comma()?;
let separator = input.expect_string()?.into_owned();
let separator = input.expect_string()?.as_ref().to_owned();
let style = parse_counter_style(context, input);
Ok(ContentItem::Counters(name, separator, style))
})),
@ -206,10 +207,10 @@
};
match result {
Some(result) => content.push(result?),
None => return Err(StyleParseError::UnexpectedFunction(name).into())
None => return Err(StyleParseError::UnexpectedFunction(name.clone()).into())
}
}
Ok(Token::Ident(ident)) => {
Ok(Token::Ident(ref ident)) => {
let valid = match_ignore_ascii_case! { &ident,
"open-quote" => { content.push(ContentItem::OpenQuote); true },
"close-quote" => { content.push(ContentItem::CloseQuote); true },
@ -219,7 +220,7 @@
_ => false,
};
if !valid {
return Err(SelectorParseError::UnexpectedIdent(ident).into())
return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
}
Err(_) => break,
@ -333,8 +334,8 @@
let mut counters = Vec::new();
loop {
let counter_name = match input.next() {
Ok(Token::Ident(ident)) => CustomIdent::from_ident(ident, &["none"])?,
Ok(t) => return Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::Ident(ref ident)) => CustomIdent::from_ident(ident, &["none"])?,
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(_) => break,
};
let counter_delta = input.try(|input| specified::parse_integer(context, input))

View file

@ -145,13 +145,13 @@ macro_rules! impl_gecko_keyword_conversions {
/// Parse a font-family value
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
if let Ok(value) = input.try(|input| input.expect_string()) {
if let Ok(value) = input.try(|i| i.expect_string_cloned()) {
return Ok(FontFamily::FamilyName(FamilyName {
name: Atom::from(&*value),
quoted: true,
}))
}
let first_ident = input.expect_ident()?;
let first_ident = input.expect_ident()?.clone();
// FIXME(bholley): The fast thing to do here would be to look up the
// string (as lowercase) in the static atoms table. We don't have an
@ -181,7 +181,7 @@ macro_rules! impl_gecko_keyword_conversions {
_ => {}
}
let mut value = first_ident.into_owned();
let mut value = first_ident.as_ref().to_owned();
// These keywords are not allowed by themselves.
// The only way this value can be valid with with another keyword.
if css_wide_keyword {
@ -189,7 +189,7 @@ macro_rules! impl_gecko_keyword_conversions {
value.push_str(" ");
value.push_str(&ident);
}
while let Ok(ident) = input.try(|input| input.expect_ident()) {
while let Ok(ident) = input.try(|i| i.expect_ident_cloned()) {
value.push_str(" ");
value.push_str(&ident);
}
@ -1189,7 +1189,8 @@ ${helpers.single_keyword_system("font-variant-caps",
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue { weight: false, style: false };
try_match_ident_ignore_ascii_case! { input.expect_ident()?,
// FIXME: remove clone() when lifetimes are non-lexical
try_match_ident_ignore_ascii_case! { input.expect_ident()?.clone(),
"none" => Ok(result),
"weight" => {
result.weight = true;
@ -1411,9 +1412,10 @@ ${helpers.single_keyword_system("font-kerning",
)
);
while let Ok(_) = input.try(|input| {
match input.next()? {
Token::Ident(ident) => {
if ident == "historical-forms" {
// FIXME: remove clone() when lifetimes are non-lexical
match input.next()?.clone() {
Token::Ident(ref ident) => {
if *ident == "historical-forms" {
check_if_parsed!(HISTORICAL_FORMS);
alternates.push(VariantAlternates::HistoricalForms);
Ok(())
@ -1421,7 +1423,7 @@ ${helpers.single_keyword_system("font-kerning",
return Err(StyleParseError::UnspecifiedError.into());
}
},
Token::Function(name) => {
Token::Function(ref name) => {
input.parse_nested_block(|i| {
match_ignore_ascii_case! { &name,
% for value in "swash stylistic ornaments annotation".split():
@ -2136,8 +2138,8 @@ https://drafts.csswg.org/css-fonts-4/#low-level-font-variation-settings-control-
if input.try(|input| input.expect_ident_matching("normal")).is_ok() {
Ok(SpecifiedValue::Normal)
} else {
input.expect_string().map(|cow| {
SpecifiedValue::Override(cow.into_owned())
input.expect_string().map(|s| {
SpecifiedValue::Override(s.as_ref().to_owned())
}).map_err(|e| e.into())
}
}

View file

@ -590,9 +590,9 @@ ${helpers.predefined_type(
return Ok(SpecifiedValue::None);
}
if let Ok(s) = input.try(|input| input.expect_string()) {
if let Ok(s) = input.try(|i| i.expect_string().map(|s| s.as_ref().to_owned())) {
// Handle <string>
return Ok(SpecifiedValue::String(s.into_owned()));
return Ok(SpecifiedValue::String(s));
}
// Handle a pair of keywords

View file

@ -94,7 +94,7 @@ ${helpers.single_keyword("list-style-position", "outside inside", animation_valu
Ok(if let Ok(style) = input.try(|i| CounterStyleOrNone::parse(context, i)) {
SpecifiedValue::CounterStyle(style)
} else {
SpecifiedValue::String(input.expect_string()?.into_owned())
SpecifiedValue::String(input.expect_string()?.as_ref().to_owned())
})
}
</%helpers:longhand>
@ -197,13 +197,13 @@ ${helpers.single_keyword("list-style-position", "outside inside", animation_valu
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::QuotedString(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(_) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::QuotedString(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => return Err(e.into()),
};
quotes.push((first, second))

View file

@ -101,7 +101,7 @@
} else {
Cursor::from_css_keyword(&ident)
.map(computed_value::Keyword::Cursor)
.map_err(|()| SelectorParseError::UnexpectedIdent(ident).into())
.map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
}
}

View file

@ -361,7 +361,7 @@ ${helpers.predefined_type("object-position",
_ => false
};
if !success {
return Err(SelectorParseError::UnexpectedIdent(ident).into());
return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into());
}
}
@ -463,8 +463,8 @@ ${helpers.predefined_type("object-position",
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
let mut strings = vec![];
while let Ok(string) = input.try(Parser::expect_string) {
strings.push(string.into_owned().into_boxed_str());
while let Ok(string) = input.try(|i| i.expect_string().map(|s| s.as_ref().into())) {
strings.push(string);
}
TemplateAreas::from_vec(strings)

View file

@ -117,17 +117,17 @@
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
match input.next()? {
Token::Ident(ident) => {
match *input.next()? {
Token::Ident(ref ident) => {
try_match_ident_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
}
}
Token::QuotedString(v) => {
Ok(Side::String(v.into_owned().into_boxed_str()))
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
other => Err(BasicParseError::UnexpectedToken(other).into()),
ref t => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
}
}
}
@ -236,7 +236,7 @@ ${helpers.single_keyword("unicode-bidi",
"blink" => if result.contains(BLINK) { Err(()) }
else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| SelectorParseError::UnexpectedIdent(ident).into())
}).map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
Err(e) => return Err(e.into())
}

View file

@ -422,7 +422,7 @@ impl CSSWideKeyword {
impl Parse for CSSWideKeyword {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let ident = input.expect_ident()?;
let ident = input.expect_ident()?.clone();
input.expect_exhausted()?;
CSSWideKeyword::from_ident(&ident)
.ok_or(SelectorParseError::UnexpectedIdent(ident).into())

View file

@ -278,12 +278,11 @@
% endfor
let first_line_names = input.try(parse_line_names).unwrap_or(vec![].into_boxed_slice());
if let Ok(s) = input.try(Parser::expect_string) {
if let Ok(mut string) = input.try(|i| i.expect_string().map(|s| s.as_ref().into())) {
let mut strings = vec![];
let mut values = vec![];
let mut line_names = vec![];
let mut names = first_line_names.into_vec();
let mut string = s.into_owned().into_boxed_str();
loop {
line_names.push(names.into_boxed_slice());
strings.push(string);
@ -294,8 +293,8 @@
names.extend(v.into_vec());
}
string = match input.try(Parser::expect_string) {
Ok(s) => s.into_owned().into_boxed_str(),
string = match input.try(|i| i.expect_string().map(|s| s.as_ref().into())) {
Ok(s) => s,
_ => { // only the named area determines whether we should bail out
line_names.push(names.into_boxed_slice());
break

View file

@ -165,7 +165,7 @@ impl Expression {
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let name = input.expect_ident()?;
let name = input.expect_ident_cloned()?;
input.expect_colon()?;
// TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name,

View file

@ -8,7 +8,7 @@
use {Atom, Prefix, Namespace, LocalName, CaseSensitivityExt};
use attr::{AttrIdentifier, AttrValue};
use cssparser::{Parser as CssParser, ToCss, serialize_identifier, CompactCowStr};
use cssparser::{Parser as CssParser, ToCss, serialize_identifier, CowRcStr};
use dom::{OpaqueNode, TElement, TNode};
use element_state::ElementState;
use fnv::FnvHashMap;
@ -20,7 +20,6 @@ use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivit
use selectors::parser::{SelectorMethods, SelectorParseError};
use selectors::visitor::SelectorVisitor;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::fmt;
use std::fmt::Debug;
use std::mem;
@ -334,7 +333,7 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
type Impl = SelectorImpl;
type Error = StyleParseError<'i>;
fn parse_non_ts_pseudo_class(&self, name: CompactCowStr<'i>)
fn parse_non_ts_pseudo_class(&self, name: CowRcStr<'i>)
-> Result<NonTSPseudoClass, ParseError<'i>> {
use self::NonTSPseudoClass::*;
let pseudo_class = match_ignore_ascii_case! { &name,
@ -367,19 +366,19 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
}
fn parse_non_ts_functional_pseudo_class<'t>(&self,
name: CompactCowStr<'i>,
name: CowRcStr<'i>,
parser: &mut CssParser<'i, 't>)
-> Result<NonTSPseudoClass, ParseError<'i>> {
use self::NonTSPseudoClass::*;
let pseudo_class = match_ignore_ascii_case!{ &name,
"lang" => {
Lang(parser.expect_ident_or_string()?.into_owned().into_boxed_str())
Lang(parser.expect_ident_or_string()?.as_ref().into())
}
"-servo-case-sensitive-type-attr" => {
if !self.in_user_agent_stylesheet() {
return Err(SelectorParseError::UnexpectedIdent(name.clone()).into());
}
ServoCaseSensitiveTypeAttr(Atom::from(Cow::from(parser.expect_ident()?)))
ServoCaseSensitiveTypeAttr(Atom::from(parser.expect_ident()?.as_ref()))
}
_ => return Err(SelectorParseError::UnexpectedIdent(name.clone()).into())
};
@ -387,7 +386,7 @@ impl<'a, 'i> ::selectors::Parser<'i> for SelectorParser<'a> {
Ok(pseudo_class)
}
fn parse_pseudo_element(&self, name: CompactCowStr<'i>) -> Result<PseudoElement, ParseError<'i>> {
fn parse_pseudo_element(&self, name: CowRcStr<'i>) -> Result<PseudoElement, ParseError<'i>> {
use self::PseudoElement::*;
let pseudo_element = match_ignore_ascii_case! { &name,
"before" => Before,

View file

@ -89,9 +89,9 @@ macro_rules! parse_quoted_or_unquoted_string {
let start = input.position();
input.parse_entirely(|input| {
match input.next() {
Ok(Token::QuotedString(value)) =>
Ok($url_matching_function(value.into_owned())),
Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::QuotedString(ref value)) =>
Ok($url_matching_function(value.as_ref().to_owned())),
Ok(t) => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => Err(e.into()),
}
}).or_else(|_: ParseError| {
@ -112,7 +112,7 @@ impl UrlMatchingFunction {
parse_quoted_or_unquoted_string!(input, UrlMatchingFunction::Domain)
} else if input.try(|input| input.expect_function_matching("regexp")).is_ok() {
input.parse_nested_block(|input| {
Ok(UrlMatchingFunction::RegExp(input.expect_string()?.into_owned()))
Ok(UrlMatchingFunction::RegExp(input.expect_string()?.as_ref().to_owned()))
})
} else if let Ok(url) = input.try(|input| SpecifiedUrl::parse(context, input)) {
Ok(UrlMatchingFunction::Url(url))

View file

@ -4,7 +4,7 @@
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser, ParserInput, CompactCowStr};
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser, ParserInput, CowRcStr};
use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule, SourceLocation};
use error_reporting::{NullReporter, ContextualParseError};
use parser::{ParserContext, log_css_error};
@ -531,7 +531,7 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for KeyframeDeclarationParser<'a, 'b> {
type Declaration = ();
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<(), ParseError<'i>> {
let id = PropertyId::parse(&name)
.map_err(|()| PropertyDeclarationParseError::UnknownProperty(name))?;

View file

@ -7,7 +7,7 @@
use {Namespace, Prefix};
use counter_style::{parse_counter_style_body, parse_counter_style_name};
use cssparser::{AtRuleParser, AtRuleType, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{CompactCowStr, SourceLocation, BasicParseError};
use cssparser::{CowRcStr, SourceLocation, BasicParseError};
use error_reporting::ContextualParseError;
use font_face::parse_font_face_block;
use media_queries::{parse_media_query_list, MediaList};
@ -18,7 +18,6 @@ use selectors::SelectorList;
use selectors::parser::SelectorParseError;
use servo_arc::Arc;
use shared_lock::{Locked, SharedRwLock};
use std::borrow::Cow;
use str::starts_with_ignore_ascii_case;
use style_traits::{StyleParseError, ParseError};
use stylesheets::{CssRule, CssRules, CssRuleType, Origin, StylesheetLoader};
@ -142,7 +141,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
fn parse_prelude<'t>(
&mut self,
name: CompactCowStr<'i>,
name: CowRcStr<'i>,
input: &mut Parser<'i, 't>
) -> Result<AtRuleType<AtRulePrelude, CssRule>, ParseError<'i>> {
let location = get_location_with_offset(input.current_source_location(),
@ -156,7 +155,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
}
self.state = State::Imports;
let url_string = input.expect_url_or_string()?.into_owned();
let url_string = input.expect_url_or_string()?.as_ref().to_owned();
let specified_url = SpecifiedUrl::parse_from_string(url_string, &self.context)?;
let media = parse_media_query_list(&self.context, input);
@ -183,14 +182,14 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
}
self.state = State::Namespaces;
let prefix_result = input.try(|input| input.expect_ident());
let prefix_result = input.try(|i| i.expect_ident_cloned());
let maybe_namespace = match input.expect_url_or_string() {
Ok(url_or_string) => url_or_string,
Err(BasicParseError::UnexpectedToken(t)) =>
return Err(StyleParseError::UnexpectedTokenWithinNamespace(t).into()),
Err(e) => return Err(e.into()),
};
let url = Namespace::from(Cow::from(maybe_namespace));
let url = Namespace::from(maybe_namespace.as_ref());
let id = register_namespace(&url)
.map_err(|()| StyleParseError::UnspecifiedError)?;
@ -198,7 +197,7 @@ impl<'a, 'i> AtRuleParser<'i> for TopLevelRuleParser<'a> {
let mut namespaces = self.namespaces.as_mut().unwrap();
let opt_prefix = if let Ok(prefix) = prefix_result {
let prefix = Prefix::from(Cow::from(prefix));
let prefix = Prefix::from(prefix.as_ref());
namespaces
.prefixes
.insert(prefix.clone(), (url.clone(), id));
@ -324,7 +323,7 @@ impl<'a, 'b, 'i> AtRuleParser<'i> for NestedRuleParser<'a, 'b> {
fn parse_prelude<'t>(
&mut self,
name: CompactCowStr<'i>,
name: CowRcStr<'i>,
input: &mut Parser<'i, 't>
) -> Result<AtRuleType<AtRulePrelude, CssRule>, ParseError<'i>> {
let location =

View file

@ -97,14 +97,14 @@ impl SupportsCondition {
// End of input
return Ok(in_parens)
}
Ok(Token::Ident(ident)) => {
Ok(&Token::Ident(ref ident)) => {
match_ignore_ascii_case! { &ident,
"and" => ("and", SupportsCondition::And as fn(_) -> _),
"or" => ("or", SupportsCondition::Or as fn(_) -> _),
_ => return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
}
Ok(t) => return Err(CssParseError::Basic(BasicParseError::UnexpectedToken(t)))
Ok(t) => return Err(CssParseError::Basic(BasicParseError::UnexpectedToken(t.clone())))
};
let mut conditions = Vec::with_capacity(2);
@ -126,7 +126,8 @@ impl SupportsCondition {
// but we want to not include it in `pos` for the SupportsCondition::FutureSyntax cases.
while input.try(Parser::expect_whitespace).is_ok() {}
let pos = input.position();
match input.next()? {
// FIXME: remove clone() when lifetimes are non-lexical
match input.next()?.clone() {
Token::ParenthesisBlock => {
let nested = input.try(|input| {
input.parse_nested_block(|i| parse_condition_or_declaration(i))
@ -244,7 +245,7 @@ impl Declaration {
let mut input = ParserInput::new(&self.0);
let mut input = Parser::new(&mut input);
input.parse_entirely(|input| {
let prop = input.expect_ident().unwrap();
let prop = input.expect_ident().unwrap().as_ref().to_owned();
input.expect_colon().unwrap();
let id = PropertyId::parse(&prop)
.map_err(|_| StyleParseError::UnspecifiedError)?;

View file

@ -10,7 +10,7 @@
use app_units::Au;
use context::QuirksMode;
use cssparser::{AtRuleParser, DeclarationListParser, DeclarationParser, Parser, parse_important};
use cssparser::{CompactCowStr, ToCss as ParserToCss};
use cssparser::{CowRcStr, ToCss as ParserToCss};
use error_reporting::ContextualParseError;
use euclid::TypedSize2D;
use font_metrics::get_metrics_provider_for_product;
@ -280,7 +280,7 @@ impl<'a, 'b, 'i> DeclarationParser<'i> for ViewportRuleParser<'a, 'b> {
type Declaration = Vec<ViewportDescriptorDeclaration>;
type Error = SelectorParseError<'i, StyleParseError<'i>>;
fn parse_value<'t>(&mut self, name: CompactCowStr<'i>, input: &mut Parser<'i, 't>)
fn parse_value<'t>(&mut self, name: CowRcStr<'i>, input: &mut Parser<'i, 't>)
-> Result<Vec<ViewportDescriptorDeclaration>, ParseError<'i>> {
macro_rules! declaration {
($declaration:ident($parse:expr)) => {

View file

@ -100,11 +100,11 @@ impl Parse for GridLine {
}
grid_line.line_num = Some(i);
} else if let Ok(name) = input.try(|i| i.expect_ident()) {
} else if let Ok(name) = input.try(|i| i.expect_ident_cloned()) {
if val_before_span || grid_line.ident.is_some() {
return Err(StyleParseError::UnspecifiedError.into());
}
grid_line.ident = Some(CustomIdent::from_ident(name, &[])?);
grid_line.ident = Some(CustomIdent::from_ident(&name, &[])?);
} else {
break
}

View file

@ -151,17 +151,20 @@ impl<T: Parse> Parse for FontSettingTag<T> {
use byteorder::{ReadBytesExt, BigEndian};
use std::io::Cursor;
let tag = input.expect_string()?;
// allowed strings of length 4 containing chars: <U+20, U+7E>
if tag.len() != 4 ||
tag.chars().any(|c| c < ' ' || c > '~')
let u_tag;
{
return Err(StyleParseError::UnspecifiedError.into())
}
let tag = input.expect_string()?;
let mut raw = Cursor::new(tag.as_bytes());
let u_tag = raw.read_u32::<BigEndian>().unwrap();
// allowed strings of length 4 containing chars: <U+20, U+7E>
if tag.len() != 4 ||
tag.chars().any(|c| c < ' ' || c > '~')
{
return Err(StyleParseError::UnspecifiedError.into())
}
let mut raw = Cursor::new(tag.as_bytes());
u_tag = raw.read_u32::<BigEndian>().unwrap();
}
Ok(FontSettingTag { tag: u_tag, value: T::parse(context, input)? })
}

View file

@ -9,11 +9,10 @@
#![deny(missing_docs)]
use Atom;
pub use cssparser::{RGBA, Token, Parser, serialize_identifier, BasicParseError, CompactCowStr};
pub use cssparser::{RGBA, Token, Parser, serialize_identifier, BasicParseError, CowRcStr};
use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseError;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::fmt::{self, Debug};
use std::hash;
use style_traits::{ToCss, ParseError, StyleParseError};
@ -87,18 +86,18 @@ pub struct CustomIdent(pub Atom);
impl CustomIdent {
/// Parse an already-tokenizer identifier
pub fn from_ident<'i>(ident: CompactCowStr<'i>, excluding: &[&str]) -> Result<Self, ParseError<'i>> {
let valid = match_ignore_ascii_case! { &ident,
pub fn from_ident<'i>(ident: &CowRcStr<'i>, excluding: &[&str]) -> Result<Self, ParseError<'i>> {
let valid = match_ignore_ascii_case! { ident,
"initial" | "inherit" | "unset" | "default" => false,
_ => true
};
if !valid {
return Err(SelectorParseError::UnexpectedIdent(ident).into());
return Err(SelectorParseError::UnexpectedIdent(ident.clone()).into());
}
if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) {
Err(StyleParseError::UnspecifiedError.into())
} else {
Ok(CustomIdent(Atom::from(Cow::from(ident))))
Ok(CustomIdent(Atom::from(ident.as_ref())))
}
}
}
@ -121,8 +120,8 @@ pub enum KeyframesName {
impl KeyframesName {
/// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name
pub fn from_ident(value: String) -> Self {
let custom_ident = CustomIdent::from_ident((&*value).into(), &["none"]).ok();
pub fn from_ident(value: &str) -> Self {
let custom_ident = CustomIdent::from_ident(&value.into(), &["none"]).ok();
match custom_ident {
Some(ident) => KeyframesName::Ident(ident),
None => KeyframesName::QuotedString(value.into()),
@ -155,9 +154,9 @@ impl hash::Hash for KeyframesName {
impl Parse for KeyframesName {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
match input.next() {
Ok(Token::Ident(s)) => Ok(KeyframesName::Ident(CustomIdent::from_ident(s, &["none"])?)),
Ok(Token::QuotedString(s)) => Ok(KeyframesName::QuotedString(Atom::from(Cow::from(s)))),
Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()),
Ok(&Token::Ident(ref s)) => Ok(KeyframesName::Ident(CustomIdent::from_ident(s, &["none"])?)),
Ok(&Token::QuotedString(ref s)) => Ok(KeyframesName::QuotedString(Atom::from(s.as_ref()))),
Ok(t) => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => Err(e.into()),
}
}

View file

@ -374,7 +374,8 @@ fn parse_normal_or_baseline<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AlignF
// <baseline-position>
fn parse_baseline<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AlignFlags, ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input.expect_ident()?,
// FIXME: remove clone() when lifetimes are non-lexical
try_match_ident_ignore_ascii_case! { input.expect_ident()?.clone(),
"baseline" => Ok(ALIGN_BASELINE),
"first" => {
input.expect_ident_matching("baseline")?;
@ -471,7 +472,7 @@ fn parse_self_position<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AlignFlags,
// [ legacy && [ left | right | center ] ]
fn parse_legacy<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AlignFlags, ParseError<'i>> {
let a = input.expect_ident()?;
let a = input.expect_ident()?.clone();
let b = input.expect_ident()?;
if a.eq_ignore_ascii_case("legacy") {
(match_ignore_ascii_case! { &b,
@ -479,7 +480,7 @@ fn parse_legacy<'i, 't>(input: &mut Parser<'i, 't>) -> Result<AlignFlags, ParseE
"right" => Ok(ALIGN_LEGACY | ALIGN_RIGHT),
"center" => Ok(ALIGN_LEGACY | ALIGN_CENTER),
_ => Err(())
}).map_err(|()| SelectorParseError::UnexpectedIdent(b).into())
}).map_err(|()| SelectorParseError::UnexpectedIdent(b.clone()).into())
} else if b.eq_ignore_ascii_case("legacy") {
(match_ignore_ascii_case! { &a,
"left" => Ok(ALIGN_LEGACY | ALIGN_LEFT),

View file

@ -27,6 +27,6 @@ impl Parse for BackgroundSize {
"cover" => Ok(GenericBackgroundSize::Cover),
"contain" => Ok(GenericBackgroundSize::Contain),
_ => Err(()),
}).map_err(|()| SelectorParseError::UnexpectedIdent(ident).into())
}).map_err(|()| SelectorParseError::UnexpectedIdent(ident.clone()).into())
}
}

View file

@ -101,7 +101,7 @@ impl Parse for GeometryBox {
impl Parse for BasicShape {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let function = input.expect_function()?;
let function = input.expect_function()?.clone();
input.parse_nested_block(move |i| {
(match_ignore_ascii_case! { &function,
"inset" => return InsetRect::parse_function_arguments(context, i).map(GenericBasicShape::Inset),
@ -109,7 +109,7 @@ impl Parse for BasicShape {
"ellipse" => return Ellipse::parse_function_arguments(context, i).map(GenericBasicShape::Ellipse),
"polygon" => return Polygon::parse_function_arguments(context, i).map(GenericBasicShape::Polygon),
_ => Err(())
}).map_err(|()| StyleParseError::UnexpectedFunction(function).into())
}).map_err(|()| StyleParseError::UnexpectedFunction(function.clone()).into())
})
}
}

View file

@ -150,40 +150,36 @@ impl CalcNode {
input: &mut Parser<'i, 't>,
expected_unit: CalcUnit
) -> Result<Self, ParseError<'i>> {
// FIXME: remove early returns when lifetimes are non-lexical
match (input.next()?, expected_unit) {
(Token::Number { value, .. }, _) => Ok(CalcNode::Number(value)),
(Token::Dimension { value, ref unit, .. }, CalcUnit::Length) |
(Token::Dimension { value, ref unit, .. }, CalcUnit::LengthOrPercentage) => {
NoCalcLength::parse_dimension(context, value, unit)
(&Token::Number { value, .. }, _) => return Ok(CalcNode::Number(value)),
(&Token::Dimension { value, ref unit, .. }, CalcUnit::Length) |
(&Token::Dimension { value, ref unit, .. }, CalcUnit::LengthOrPercentage) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(CalcNode::Length)
.map_err(|()| StyleParseError::UnspecifiedError.into())
}
(Token::Dimension { value, ref unit, .. }, CalcUnit::Angle) => {
Angle::parse_dimension(value, unit, /* from_calc = */ true)
(&Token::Dimension { value, ref unit, .. }, CalcUnit::Angle) => {
return Angle::parse_dimension(value, unit, /* from_calc = */ true)
.map(CalcNode::Angle)
.map_err(|()| StyleParseError::UnspecifiedError.into())
}
(Token::Dimension { value, ref unit, .. }, CalcUnit::Time) => {
Time::parse_dimension(value, unit, /* from_calc = */ true)
(&Token::Dimension { value, ref unit, .. }, CalcUnit::Time) => {
return Time::parse_dimension(value, unit, /* from_calc = */ true)
.map(CalcNode::Time)
.map_err(|()| StyleParseError::UnspecifiedError.into())
}
(Token::Percentage { unit_value, .. }, CalcUnit::LengthOrPercentage) |
(Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => {
Ok(CalcNode::Percentage(unit_value))
(&Token::Percentage { unit_value, .. }, CalcUnit::LengthOrPercentage) |
(&Token::Percentage { unit_value, .. }, CalcUnit::Percentage) => {
return Ok(CalcNode::Percentage(unit_value))
}
(Token::ParenthesisBlock, _) => {
input.parse_nested_block(|i| {
CalcNode::parse(context, i, expected_unit)
})
}
(Token::Function(ref name), _) if name.eq_ignore_ascii_case("calc") => {
input.parse_nested_block(|i| {
CalcNode::parse(context, i, expected_unit)
})
}
(t, _) => Err(BasicParseError::UnexpectedToken(t).into())
(&Token::ParenthesisBlock, _) => {}
(&Token::Function(ref name), _) if name.eq_ignore_ascii_case("calc") => {}
(t, _) => return Err(BasicParseError::UnexpectedToken(t.clone()).into())
}
input.parse_nested_block(|i| {
CalcNode::parse(context, i, expected_unit)
})
}
/// Parse a top-level `calc` expression, with all nested sub-expressions.
@ -200,11 +196,12 @@ impl CalcNode {
loop {
let position = input.position();
match input.next_including_whitespace() {
Ok(Token::WhiteSpace(_)) => {
Ok(&Token::WhiteSpace(_)) => {
if input.is_exhausted() {
break; // allow trailing whitespace
}
match input.next()? {
// FIXME: remove clone() when lifetimes are non-lexical
match input.next()?.clone() {
Token::Delim('+') => {
let rhs =
Self::parse_product(context, input, expected_unit)?;
@ -252,13 +249,13 @@ impl CalcNode {
loop {
let position = input.position();
match input.next() {
Ok(Token::Delim('*')) => {
Ok(&Token::Delim('*')) => {
let rhs = Self::parse_one(context, input, expected_unit)?;
let new_root = CalcNode::Mul(Box::new(root), Box::new(rhs));
root = new_root;
}
// TODO(emilio): Figure out why the `Integer` check.
Ok(Token::Delim('/')) if expected_unit != CalcUnit::Integer => {
Ok(&Token::Delim('/')) if expected_unit != CalcUnit::Integer => {
let rhs = Self::parse_one(context, input, expected_unit)?;
let new_root = CalcNode::Div(Box::new(root), Box::new(rhs));
root = new_root;

View file

@ -72,7 +72,7 @@ impl Parse for Color {
// specified value.
let start_position = input.position();
let authored = match input.next() {
Ok(Token::Ident(s)) => Some(s.to_lowercase().into_boxed_str()),
Ok(&Token::Ident(ref s)) => Some(s.to_lowercase().into_boxed_str()),
_ => None,
};
input.reset(start_position);
@ -173,22 +173,22 @@ impl Color {
///
/// https://quirks.spec.whatwg.org/#the-hashless-hex-color-quirk
fn parse_quirky_color<'i, 't>(input: &mut Parser<'i, 't>) -> Result<RGBA, ParseError<'i>> {
let (value, unit) = match input.next()? {
let (value, unit) = match *input.next()? {
Token::Number { int_value: Some(integer), .. } => {
(integer, None)
},
Token::Dimension { int_value: Some(integer), unit, .. } => {
Token::Dimension { int_value: Some(integer), ref unit, .. } => {
(integer, Some(unit))
},
Token::Ident(ident) => {
Token::Ident(ref ident) => {
if ident.len() != 3 && ident.len() != 6 {
return Err(StyleParseError::UnspecifiedError.into());
}
return parse_hash_color(ident.as_bytes())
.map_err(|()| StyleParseError::UnspecifiedError.into());
}
t => {
return Err(BasicParseError::UnexpectedToken(t).into());
ref t => {
return Err(BasicParseError::UnexpectedToken(t.clone()).into());
},
};
if value < 0 {

View file

@ -159,7 +159,7 @@ impl Parse for Filter {
return Ok(GenericFilter::Url(url));
}
}
let function = input.expect_function()?;
let function = input.expect_function()?.clone();
input.parse_nested_block(|i| {
try_match_ident_ignore_ascii_case! { function,
"blur" => Ok(GenericFilter::Blur(Length::parse_non_negative(context, i)?)),

View file

@ -18,10 +18,10 @@ use values::specified::LengthOrPercentage;
/// Parse a single flexible length.
pub fn parse_flex<'i, 't>(input: &mut Parser<'i, 't>) -> Result<CSSFloat, ParseError<'i>> {
match input.next()? {
match *input.next()? {
Token::Dimension { value, ref unit, .. } if unit.eq_ignore_ascii_case("fr") && value.is_sign_positive()
=> Ok(value),
t => Err(BasicParseError::UnexpectedToken(t).into()),
ref t => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
}
}
@ -85,8 +85,8 @@ pub fn parse_line_names<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Box<[Custo
input.expect_square_bracket_block()?;
input.parse_nested_block(|input| {
let mut values = vec![];
while let Ok(ident) = input.try(|i| i.expect_ident()) {
let ident = CustomIdent::from_ident(ident, &["span"])?;
while let Ok(ident) = input.try(|i| i.expect_ident_cloned()) {
let ident = CustomIdent::from_ident(&ident, &["span"])?;
values.push(ident);
}

View file

@ -13,7 +13,6 @@ use parser::{Parse, ParserContext};
use selectors::parser::SelectorParseError;
#[cfg(feature = "servo")]
use servo_url::ServoUrl;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::f32::consts::PI;
use std::fmt;
@ -169,9 +168,9 @@ impl Image {
fn parse_element<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Atom, ParseError<'i>> {
input.try(|i| i.expect_function_matching("-moz-element"))?;
input.parse_nested_block(|i| {
match i.next()? {
Token::IDHash(id) => Ok(Atom::from(Cow::from(id))),
t => Err(BasicParseError::UnexpectedToken(t).into()),
match *i.next()? {
Token::IDHash(ref id) => Ok(Atom::from(id.as_ref())),
ref t => Err(BasicParseError::UnexpectedToken(t.clone()).into()),
}
})
}
@ -184,7 +183,8 @@ impl Parse for Gradient {
Radial,
}
let func = input.expect_function()?;
// FIXME: remove clone() when lifetimes are non-lexical
let func = input.expect_function()?.clone();
let result = match_ignore_ascii_case! { &func,
"linear-gradient" => {
Some((Shape::Linear, false, CompatMode::Modern))
@ -234,7 +234,7 @@ impl Parse for Gradient {
let (shape, repeating, mut compat_mode) = match result {
Some(result) => result,
None => return Err(StyleParseError::UnexpectedFunction(func).into()),
None => return Err(StyleParseError::UnexpectedFunction(func.clone()).into()),
};
let (kind, items) = input.parse_nested_block(|i| {
@ -389,7 +389,7 @@ impl Gradient {
}
}
let ident = input.expect_ident()?;
let ident = input.expect_ident_cloned()?;
input.expect_comma()?;
let (kind, reverse_stops) = match_ignore_ascii_case! { &ident,
@ -439,7 +439,7 @@ impl Gradient {
let mut items = input.try(|i| {
i.expect_comma()?;
i.parse_comma_separated(|i| {
let function = i.expect_function()?;
let function = i.expect_function()?.clone();
let (color, mut p) = i.parse_nested_block(|i| {
let p = match_ignore_ascii_case! { &function,
"color-stop" => {
@ -879,7 +879,7 @@ impl Parse for PaintWorklet {
input.parse_nested_block(|i| {
let name = i.expect_ident()?;
Ok(PaintWorklet {
name: Atom::from(Cow::from(name)),
name: Atom::from(name.as_ref()),
})
})
}
@ -890,7 +890,7 @@ impl Parse for MozImageRect {
input.try(|i| i.expect_function_matching("-moz-image-rect"))?;
input.parse_nested_block(|i| {
let string = i.expect_url_or_string()?;
let url = SpecifiedUrl::parse_from_string(string.into_owned(), context)?;
let url = SpecifiedUrl::parse_from_string(string.as_ref().to_owned(), context)?;
i.expect_comma()?;
let top = NumberOrPercentage::parse_non_negative(context, i)?;
i.expect_comma()?;

View file

@ -619,26 +619,29 @@ impl Length {
num_context: AllowedLengthType,
allow_quirks: AllowQuirks)
-> Result<Length, ParseError<'i>> {
let token = input.next()?;
match token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
Length::parse_dimension(context, value, unit)
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
// FIXME: remove early returns when lifetimes are non-lexical
{
let token = input.next()?;
match *token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
return Length::parse_dimension(context, value, unit)
.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
Ok(Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(value))))
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
return input.parse_nested_block(|input| {
CalcNode::parse_length(context, input, num_context).map(|calc| Length::Calc(Box::new(calc)))
})
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
}
return Ok(Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(value))))
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
ref token => return Err(BasicParseError::UnexpectedToken(token.clone()).into())
}
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}
input.parse_nested_block(|input| {
CalcNode::parse_length(context, input, num_context).map(|calc| Length::Calc(Box::new(calc)))
})
}
/// Parse a non-negative length
@ -761,24 +764,25 @@ impl Percentage {
input: &mut Parser<'i, 't>,
num_context: AllowedNumericType,
) -> Result<Self, ParseError<'i>> {
match input.next()? {
// FIXME: remove early returns when lifetimes are non-lexical
match *input.next()? {
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
Ok(Percentage::new(unit_value))
return Ok(Percentage::new(unit_value))
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let result = input.parse_nested_block(|i| {
CalcNode::parse_percentage(context, i)
})?;
// TODO(emilio): -moz-image-rect is the only thing that uses
// the clamping mode... I guess we could disallow it...
Ok(Percentage {
value: result,
calc_clamping_mode: Some(num_context),
})
}
t => Err(BasicParseError::UnexpectedToken(t).into())
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into())
}
let result = input.parse_nested_block(|i| {
CalcNode::parse_percentage(context, i)
})?;
// TODO(emilio): -moz-image-rect is the only thing that uses
// the clamping mode... I guess we could disallow it...
Ok(Percentage {
value: result,
calc_clamping_mode: Some(num_context),
})
}
/// Parses a percentage token, but rejects it if it's negative.
@ -877,31 +881,36 @@ impl LengthOrPercentage {
allow_quirks: AllowQuirks)
-> Result<LengthOrPercentage, ParseError<'i>>
{
let token = input.next()?;
match token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
NoCalcLength::parse_dimension(context, value, unit).map(LengthOrPercentage::Length)
}
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
return Ok(LengthOrPercentage::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
Err(())
} else {
return Ok(LengthOrPercentage::Length(NoCalcLength::from_px(value)))
// FIXME: remove early returns when lifetimes are non-lexical
{
let token = input.next()?;
match *token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentage::Length)
.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
return Ok(LengthOrPercentage::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(BasicParseError::UnexpectedToken(token.clone()).into())
} else {
return Ok(LengthOrPercentage::Length(NoCalcLength::from_px(value)))
}
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
_ => return Err(BasicParseError::UnexpectedToken(token.clone()).into())
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
return Ok(LengthOrPercentage::Calc(Box::new(calc)))
}
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentage::Calc(Box::new(calc)))
}
/// Parse a non-negative length.
@ -1013,35 +1022,40 @@ impl LengthOrPercentageOrAuto {
num_context: AllowedLengthType,
allow_quirks: AllowQuirks)
-> Result<Self, ParseError<'i>> {
let token = input.next()?;
match token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
NoCalcLength::parse_dimension(context, value, unit).map(LengthOrPercentageOrAuto::Length)
}
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
Ok(LengthOrPercentageOrAuto::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
// FIXME: remove early returns when lifetimes are non-lexical
{
let token = input.next()?;
match *token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrAuto::Length)
.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
Ok(LengthOrPercentageOrAuto::Length(
NoCalcLength::Absolute(AbsoluteLength::Px(value))
))
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
return Ok(LengthOrPercentageOrAuto::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
}
return Ok(LengthOrPercentageOrAuto::Length(
NoCalcLength::Absolute(AbsoluteLength::Px(value))
))
}
Token::Ident(ref value) if value.eq_ignore_ascii_case("auto") => {
return Ok(LengthOrPercentageOrAuto::Auto)
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
_ => return Err(BasicParseError::UnexpectedToken(token.clone()).into())
}
Token::Ident(ref value) if value.eq_ignore_ascii_case("auto") => {
Ok(LengthOrPercentageOrAuto::Auto)
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc)))
}
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrAuto::Calc(Box::new(calc)))
}
/// Parse a non-negative length, percentage, or auto.
@ -1112,33 +1126,39 @@ impl LengthOrPercentageOrNone {
allow_quirks: AllowQuirks)
-> Result<LengthOrPercentageOrNone, ParseError<'i>>
{
let token = input.next()?;
match token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
NoCalcLength::parse_dimension(context, value, unit).map(LengthOrPercentageOrNone::Length)
}
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
Ok(LengthOrPercentageOrNone::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
// FIXME: remove early returns when lifetimes are non-lexical
{
let token = input.next()?;
match *token {
Token::Dimension { value, ref unit, .. } if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthOrPercentageOrNone::Length)
.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
Ok(LengthOrPercentageOrNone::Length(
NoCalcLength::Absolute(AbsoluteLength::Px(value))
))
Token::Percentage { unit_value, .. } if num_context.is_ok(context.parsing_mode, unit_value) => {
return Ok(LengthOrPercentageOrNone::Percentage(computed::Percentage(unit_value)))
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. && !context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode) {
return Err(StyleParseError::UnspecifiedError.into())
}
return Ok(LengthOrPercentageOrNone::Length(
NoCalcLength::Absolute(AbsoluteLength::Px(value))
))
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
Token::Ident(ref value) if value.eq_ignore_ascii_case("none") => {
return Ok(LengthOrPercentageOrNone::None)
}
_ => return Err(BasicParseError::UnexpectedToken(token.clone()).into())
}
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrNone::Calc(Box::new(calc)))
}
Token::Ident(ref value) if value.eq_ignore_ascii_case("none") =>
Ok(LengthOrPercentageOrNone::None),
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}
let calc = input.parse_nested_block(|i| {
CalcNode::parse_length_or_percentage(context, i, num_context)
})?;
Ok(LengthOrPercentageOrNone::Calc(Box::new(calc)))
}
/// Parse a non-negative LengthOrPercentageOrNone.

View file

@ -12,7 +12,6 @@ use cssparser::{Parser, Token, serialize_identifier, BasicParseError};
use parser::{ParserContext, Parse};
use self::url::SpecifiedUrl;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use std::f32;
use std::fmt;
use style_traits::{ToCss, ParseError, StyleParseError};
@ -83,7 +82,7 @@ pub use ::gecko::url::*;
impl Parse for SpecifiedUrl {
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let url = input.expect_url()?;
Self::parse_from_string(url.into_owned(), context)
Self::parse_from_string(url.as_ref().to_owned(), context)
}
}
@ -98,17 +97,18 @@ no_viewport_percentage!(SpecifiedUrl);
/// Parse an `<integer>` value, handling `calc()` correctly.
pub fn parse_integer<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Integer, ParseError<'i>> {
match input.next()? {
Token::Number { int_value: Some(v), .. } => Ok(Integer::new(v)),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let result = input.parse_nested_block(|i| {
CalcNode::parse_integer(context, i)
})?;
Ok(Integer::from_calc(result))
}
t => Err(BasicParseError::UnexpectedToken(t).into())
// FIXME: remove early returns when lifetimes are non-lexical
match *input.next()? {
Token::Number { int_value: Some(v), .. } => return Ok(Integer::new(v)),
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into())
}
let result = input.parse_nested_block(|i| {
CalcNode::parse_integer(context, i)
})?;
Ok(Integer::from_calc(result))
}
/// Parse a `<number>` value, handling `calc()` correctly, and without length
@ -123,25 +123,26 @@ pub fn parse_number_with_clamping_mode<'i, 't>(context: &ParserContext,
input: &mut Parser<'i, 't>,
clamping_mode: AllowedNumericType)
-> Result<Number, ParseError<'i>> {
match input.next()? {
// FIXME: remove early returns when lifetimes are non-lexical
match *input.next()? {
Token::Number { value, .. } if clamping_mode.is_ok(context.parsing_mode, value) => {
Ok(Number {
return Ok(Number {
value: value.min(f32::MAX).max(f32::MIN),
calc_clamping_mode: None,
})
},
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {
let result = input.parse_nested_block(|i| {
CalcNode::parse_number(context, i)
})?;
Ok(Number {
value: result.min(f32::MAX).max(f32::MIN),
calc_clamping_mode: Some(clamping_mode),
})
}
t => Err(BasicParseError::UnexpectedToken(t).into())
Token::Function(ref name) if name.eq_ignore_ascii_case("calc") => {}
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into())
}
let result = input.parse_nested_block(|i| {
CalcNode::parse_number(context, i)
})?;
Ok(Number {
value: result.min(f32::MAX).max(f32::MIN),
calc_clamping_mode: Some(clamping_mode),
})
}
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq)]
@ -228,7 +229,8 @@ impl Angle {
impl Parse for Angle {
/// Parses an angle according to CSS-VALUES § 6.1.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let token = input.next()?;
// FIXME: remove clone() when lifetimes are non-lexical
let token = input.next()?.clone();
match token {
Token::Dimension { value, ref unit, .. } => {
Angle::parse_dimension(value, unit, /* from_calc = */ false)
@ -237,7 +239,7 @@ impl Parse for Angle {
return input.parse_nested_block(|i| CalcNode::parse_angle(context, i))
}
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
}
@ -268,7 +270,8 @@ impl Angle {
/// https://github.com/w3c/csswg-drafts/issues/1162 is resolved.
pub fn parse_with_unitless<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
let token = input.next()?;
// FIXME: remove clone() when lifetimes are non-lexical
let token = input.next()?.clone();
match token {
Token::Dimension { value, ref unit, .. } => {
Angle::parse_dimension(value, unit, /* from_calc = */ false)
@ -278,7 +281,7 @@ impl Angle {
return input.parse_nested_block(|i| CalcNode::parse_angle(context, i))
}
_ => Err(())
}.map_err(|()| BasicParseError::UnexpectedToken(token).into())
}.map_err(|()| BasicParseError::UnexpectedToken(token.clone()).into())
}
}
@ -366,24 +369,24 @@ impl Time {
-> Result<Self, ParseError<'i>> {
use style_traits::PARSING_MODE_DEFAULT;
// FIXME: remove early returns when lifetimes are non-lexical
match input.next() {
// Note that we generally pass ParserContext to is_ok() to check
// that the ParserMode of the ParserContext allows all numeric
// values for SMIL regardless of clamping_mode, but in this Time
// value case, the value does not animate for SMIL at all, so we use
// PARSING_MODE_DEFAULT directly.
Ok(Token::Dimension { value, ref unit, .. }) if clamping_mode.is_ok(PARSING_MODE_DEFAULT, value) => {
Time::parse_dimension(value, unit, /* from_calc = */ false)
Ok(&Token::Dimension { value, ref unit, .. }) if clamping_mode.is_ok(PARSING_MODE_DEFAULT, value) => {
return Time::parse_dimension(value, unit, /* from_calc = */ false)
.map_err(|()| StyleParseError::UnspecifiedError.into())
}
Ok(Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(PARSING_MODE_DEFAULT, time.seconds) => Ok(time),
_ => Err(StyleParseError::UnspecifiedError.into()),
}
}
Ok(t) => Err(BasicParseError::UnexpectedToken(t).into()),
Err(e) => Err(e.into())
Ok(&Token::Function(ref name)) if name.eq_ignore_ascii_case("calc") => {}
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => return Err(e.into())
}
match input.parse_nested_block(|i| CalcNode::parse_time(context, i)) {
Ok(time) if clamping_mode.is_ok(PARSING_MODE_DEFAULT, time.seconds) => Ok(time),
_ => Err(StyleParseError::UnspecifiedError.into()),
}
}
@ -814,10 +817,7 @@ impl ClipRect {
}
}
let func = input.expect_function()?;
if !func.eq_ignore_ascii_case("rect") {
return Err(StyleParseError::UnexpectedFunction(func).into())
}
input.expect_function_matching("rect")?;
input.parse_nested_block(|input| {
let top = parse_argument(context, input, allow_quirks)?;
@ -939,20 +939,20 @@ impl Attr {
-> Result<Attr, ParseError<'i>> {
// Syntax is `[namespace? `|`]? ident`
// no spaces allowed
let first = input.try(|i| i.expect_ident()).ok();
if let Ok(token) = input.try(|i| i.next_including_whitespace()) {
let first = input.try(|i| i.expect_ident_cloned()).ok();
if let Ok(token) = input.try(|i| i.next_including_whitespace().map(|t| t.clone())) {
match token {
Token::Delim('|') => {}
t => return Err(BasicParseError::UnexpectedToken(t).into()),
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
}
// must be followed by an ident
let second_token = match input.next_including_whitespace()? {
Token::Ident(second) => second,
t => return Err(BasicParseError::UnexpectedToken(t).into()),
let second_token = match *input.next_including_whitespace()? {
Token::Ident(ref second) => second,
ref t => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
};
let ns_with_id = if let Some(ns) = first {
let ns = Namespace::from(Cow::from(ns));
let ns = Namespace::from(ns.as_ref());
let id: Result<_, ParseError> =
get_id_for_namespace(&ns, context)
.map_err(|()| StyleParseError::UnspecifiedError.into());
@ -962,14 +962,14 @@ impl Attr {
};
return Ok(Attr {
namespace: ns_with_id,
attribute: second_token.into_owned(),
attribute: second_token.as_ref().to_owned(),
})
}
if let Some(first) = first {
Ok(Attr {
namespace: None,
attribute: first.into_owned(),
attribute: first.as_ref().to_owned(),
})
} else {
Err(StyleParseError::UnspecifiedError.into())

View file

@ -73,7 +73,7 @@ impl Parse for LineHeight {
ref ident if ident.eq_ignore_ascii_case("-moz-block-height") => {
Ok(GenericLineHeight::MozBlockHeight)
},
ident => Err(SelectorParseError::UnexpectedIdent(ident).into()),
ident => Err(SelectorParseError::UnexpectedIdent(ident.clone()).into()),
}
}
}

View file

@ -147,7 +147,7 @@ impl Parse for TimingFunction {
if let Ok(keyword) = input.try(TimingKeyword::parse) {
return Ok(GenericTimingFunction::Keyword(keyword));
}
if let Ok(ident) = input.try(|i| i.expect_ident()) {
if let Ok(ident) = input.try(|i| i.expect_ident_cloned()) {
let position = match_ignore_ascii_case! { &ident,
"step-start" => StepPosition::Start,
"step-end" => StepPosition::End,
@ -155,7 +155,7 @@ impl Parse for TimingFunction {
};
return Ok(GenericTimingFunction::Steps(Integer::new(1), position));
}
let function = input.expect_function()?;
let function = input.expect_function()?.clone();
input.parse_nested_block(move |i| {
(match_ignore_ascii_case! { &function,
"cubic-bezier" => {
@ -190,7 +190,7 @@ impl Parse for TimingFunction {
}
},
_ => Err(()),
}).map_err(|()| StyleParseError::UnexpectedFunction(function).into())
}).map_err(|()| StyleParseError::UnexpectedFunction(function.clone()).into())
})
}
}