Skip to content

Return more specific errors from parsing APIs #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 18, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Return more specific parse error data.
  • Loading branch information
jdm committed May 18, 2017
commit 04bef8c424dd7310f0a48fcd24d7632b0566113c
85 changes: 44 additions & 41 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use std::fmt;
use std::f32::consts::PI;

use super::{Token, Parser, ToCss};
use super::{Token, Parser, ToCss, ParseError};
use tokenizer::NumericValue;

#[cfg(feature = "serde")]
Expand Down Expand Up @@ -141,46 +141,47 @@ impl Color {
/// Parse a <color> value, per CSS Color Module Level 3.
///
/// FIXME(#2) Deprecated CSS2 System Colors are not supported yet.
pub fn parse(input: &mut Parser) -> Result<Color, ()> {
match try!(input.next()) {
Token::Hash(value) | Token::IDHash(value) => {
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Color, ParseError<'i>> {
let token = try!(input.next());
match token {
Token::Hash(ref value) | Token::IDHash(ref value) => {
Color::parse_hash(value.as_bytes())
},
Token::Ident(value) => parse_color_keyword(&*value),
Token::Function(name) => {
input.parse_nested_block(|arguments| {
Token::Ident(ref value) => parse_color_keyword(&*value),
Token::Function(ref name) => {
return input.parse_nested_block(|arguments| {
parse_color_function(&*name, arguments)
})
});
}
_ => Err(())
}
}.map_err(|()| ParseError::UnexpectedToken(token))
}

/// Parse a color hash, without the leading '#' character.
#[inline]
pub fn parse_hash(value: &[u8]) -> Result<Self, ()> {
match value.len() {
8 => rgba(
8 => Ok(rgba(
try!(from_hex(value[0])) * 16 + try!(from_hex(value[1])),
try!(from_hex(value[2])) * 16 + try!(from_hex(value[3])),
try!(from_hex(value[4])) * 16 + try!(from_hex(value[5])),
try!(from_hex(value[6])) * 16 + try!(from_hex(value[7])),
try!(from_hex(value[6])) * 16 + try!(from_hex(value[7]))),
),
6 => rgb(
6 => Ok(rgb(
try!(from_hex(value[0])) * 16 + try!(from_hex(value[1])),
try!(from_hex(value[2])) * 16 + try!(from_hex(value[3])),
try!(from_hex(value[4])) * 16 + try!(from_hex(value[5])),
try!(from_hex(value[4])) * 16 + try!(from_hex(value[5]))),
),
4 => rgba(
4 => Ok(rgba(
try!(from_hex(value[0])) * 17,
try!(from_hex(value[1])) * 17,
try!(from_hex(value[2])) * 17,
try!(from_hex(value[3])) * 17,
try!(from_hex(value[3])) * 17),
),
3 => rgb(
3 => Ok(rgb(
try!(from_hex(value[0])) * 17,
try!(from_hex(value[1])) * 17,
try!(from_hex(value[2])) * 17,
try!(from_hex(value[2])) * 17),
),
_ => Err(())
}
Expand All @@ -190,13 +191,13 @@ impl Color {


#[inline]
fn rgb(red: u8, green: u8, blue: u8) -> Result<Color, ()> {
fn rgb(red: u8, green: u8, blue: u8) -> Color {
rgba(red, green, blue, 255)
}

#[inline]
fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Result<Color, ()> {
Ok(Color::RGBA(RGBA::new(red, green, blue, alpha)))
fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Color {
Color::RGBA(RGBA::new(red, green, blue, alpha))
}


Expand Down Expand Up @@ -410,11 +411,11 @@ fn clamp_floor_256_f32(val: f32) -> u8 {
}

#[inline]
fn parse_color_function(name: &str, arguments: &mut Parser) -> Result<Color, ()> {
fn parse_color_function<'i, 't>(name: &str, arguments: &mut Parser<'i, 't>) -> Result<Color, ParseError<'i>> {
let (red, green, blue, uses_commas) = match_ignore_ascii_case! { name,
"rgb" | "rgba" => parse_rgb_components_rgb(arguments)?,
"hsl" | "hsla" => parse_rgb_components_hsl(arguments)?,
_ => return Err(())
_ => return Err(ParseError::UnexpectedToken(Token::Ident(name.to_owned().into()))),
};

let alpha = if !arguments.is_exhausted() {
Expand All @@ -423,7 +424,7 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result<Color, ()>
} else {
match try!(arguments.next()) {
Token::Delim('/') => {},
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t)),
};
};
let token = try!(arguments.next());
Expand All @@ -434,21 +435,21 @@ fn parse_color_function(name: &str, arguments: &mut Parser) -> Result<Color, ()>
Token::Percentage(ref v) => {
clamp_unit_f32(v.unit_value)
}
_ => {
return Err(())
t => {
return Err(ParseError::UnexpectedToken(t))
}
}
} else {
255
};

try!(arguments.expect_exhausted());
rgba(red, green, blue, alpha)
Ok(rgba(red, green, blue, alpha))
}


#[inline]
fn parse_rgb_components_rgb(arguments: &mut Parser) -> Result<(u8, u8, u8, bool), ()> {
fn parse_rgb_components_rgb<'i, 't>(arguments: &mut Parser<'i, 't>) -> Result<(u8, u8, u8, bool), ParseError<'i>> {
let red: u8;
let green: u8;
let blue: u8;
Expand All @@ -465,7 +466,7 @@ fn parse_rgb_components_rgb(arguments: &mut Parser) -> Result<(u8, u8, u8, bool)
uses_commas = true;
try!(arguments.expect_number())
}
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t))
});
if uses_commas {
try!(arguments.expect_comma());
Expand All @@ -480,36 +481,38 @@ fn parse_rgb_components_rgb(arguments: &mut Parser) -> Result<(u8, u8, u8, bool)
uses_commas = true;
try!(arguments.expect_percentage())
}
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t))
});
if uses_commas {
try!(arguments.expect_comma());
}
blue = clamp_unit_f32(try!(arguments.expect_percentage()));
}
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t))
};
return Ok((red, green, blue, uses_commas));
}

#[inline]
fn parse_rgb_components_hsl(arguments: &mut Parser) -> Result<(u8, u8, u8, bool), ()> {
fn parse_rgb_components_hsl<'i, 't>(arguments: &mut Parser<'i, 't>) -> Result<(u8, u8, u8, bool), ParseError<'i>> {
let mut uses_commas = false;
// Hue given as an angle
// https://drafts.csswg.org/css-values/#angles
let hue_degrees = match try!(arguments.next()) {
Token::Number(NumericValue { value: v, .. }) => v,
Token::Dimension(NumericValue { value: v, .. }, unit) => {
let token = try!(arguments.next());
let hue_degrees = match token {
Token::Number(NumericValue { value: v, .. }) => Ok(v),
Token::Dimension(NumericValue { value: v, .. }, ref unit) => {
match_ignore_ascii_case! { &*unit,
"deg" => v,
"grad" => v * 360. / 400.,
"rad" => v * 360. / (2. * PI),
"turn" => v * 360.,
_ => return Err(())
"deg" => Ok(v),
"grad" => Ok(v * 360. / 400.),
"rad" => Ok(v * 360. / (2. * PI)),
"turn" => Ok(v * 360.),
_ => Err(()),
}
}
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t))
};
let hue_degrees = try!(hue_degrees.map_err(|()| ParseError::UnexpectedToken(token)));
// Subtract an integer before rounding, to avoid some rounding errors:
let hue_normalized_degrees = hue_degrees - 360. * (hue_degrees / 360.).floor();
let hue = hue_normalized_degrees / 360.;
Expand All @@ -522,7 +525,7 @@ fn parse_rgb_components_hsl(arguments: &mut Parser) -> Result<(u8, u8, u8, bool)
uses_commas = true;
try!(arguments.expect_percentage())
}
_ => return Err(())
t => return Err(ParseError::UnexpectedToken(t))
};
let saturation = saturation.max(0.).min(1.);

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub use from_bytes::{stylesheet_encoding, EncodingSupport};
pub use color::{RGBA, Color, parse_color_keyword};
pub use nth::parse_nth;
pub use serializer::{ToCss, CssStringWriter, serialize_identifier, serialize_string, TokenSerializationType};
pub use parser::{Parser, Delimiter, Delimiters, SourcePosition};
pub use parser::{Parser, Delimiter, Delimiters, SourcePosition, ParseError};
pub use unicode_range::UnicodeRange;

// For macros
Expand Down
88 changes: 55 additions & 33 deletions src/nth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,76 +4,98 @@

use std::ascii::AsciiExt;

use super::{Token, Parser};
use super::{Token, Parser, ParseError};


/// Parse the *An+B* notation, as found in the `:nth-child()` selector.
/// The input is typically the arguments of a function,
/// in which case the caller needs to check if the arguments’ parser is exhausted.
/// Return `Ok((A, B))`, or `Err(())` for a syntax error.
pub fn parse_nth(input: &mut Parser) -> Result<(i32, i32), ()> {
match try!(input.next()) {
Token::Number(value) => Ok((0, try!(value.int_value.ok_or(())) as i32)),
Token::Dimension(value, unit) => {
let a = try!(value.int_value.ok_or(())) as i32;
match_ignore_ascii_case! { &unit,
"n" => parse_b(input, a),
"n-" => parse_signless_b(input, a, -1),
_ => Ok((a, try!(parse_n_dash_digits(&*unit))))
pub fn parse_nth<'i, 't>(input: &mut Parser<'i, 't>) -> Result<(i32, i32), ParseError<'i>> {
let token = try!(input.next());
match token {
Token::Number(ref value) => {
match value.int_value {
Some(v) => Ok((0, v as i32)),
None => Err(()),
}
}
Token::Ident(value) => {
Token::Dimension(value, ref unit) => {
match value.int_value {
Some(v) => {
let a = v as i32;
match_ignore_ascii_case! {
&unit,
"n" => Ok(try!(parse_b(input, a))),
"n-" => Ok(try!(parse_signless_b(input, a, -1))),
_ => {
parse_n_dash_digits(&*unit).map(|val| (a, val))
}
}
}
None => Err(()),
}
}
Token::Ident(ref value) => {
match_ignore_ascii_case! { &value,
"even" => Ok((2, 0)),
"odd" => Ok((2, 1)),
"n" => parse_b(input, 1),
"-n" => parse_b(input, -1),
"n-" => parse_signless_b(input, 1, -1),
"-n-" => parse_signless_b(input, -1, -1),
"n" => Ok(try!(parse_b(input, 1))),
"-n" => Ok(try!(parse_b(input, -1))),
"n-" => Ok(try!(parse_signless_b(input, 1, -1))),
"-n-" => Ok(try!(parse_signless_b(input, -1, -1))),
_ => if value.starts_with("-") {
Ok((-1, try!(parse_n_dash_digits(&value[1..]))))
parse_n_dash_digits(&value[1..]).map(|v| (-1, v))
} else {
Ok((1, try!(parse_n_dash_digits(&*value))))
parse_n_dash_digits(&*value).map(|v| (1, v))
}
}
}
Token::Delim('+') => match try!(input.next_including_whitespace()) {
Token::Ident(value) => {
match_ignore_ascii_case! { &value,
"n" => parse_b(input, 1),
"n-" => parse_signless_b(input, 1, -1),
_ => Ok((1, try!(parse_n_dash_digits(&*value))))
"n" => Ok(try!(parse_b(input, 1))),
"n-" => Ok(try!(parse_signless_b(input, 1, -1))),
_ => parse_n_dash_digits(&*value).map(|v| (1, v))
}
}
_ => Err(())
t => return Err(ParseError::UnexpectedToken(t)),
},
_ => Err(())
}
_ => Err(()),
}.map_err(|()| ParseError::UnexpectedToken(token))
}


fn parse_b(input: &mut Parser, a: i32) -> Result<(i32, i32), ()> {
fn parse_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32) -> Result<(i32, i32), ParseError<'i>> {
let start_position = input.position();
match input.next() {
Ok(Token::Delim('+')) => parse_signless_b(input, a, 1),
Ok(Token::Delim('-')) => parse_signless_b(input, a, -1),
let token = input.next();
match token {
Ok(Token::Delim('+')) => Ok(try!(parse_signless_b(input, a, 1))),
Ok(Token::Delim('-')) => Ok(try!(parse_signless_b(input, a, -1))),
Ok(Token::Number(ref value)) if value.has_sign => {
Ok((a, try!(value.int_value.ok_or(())) as i32))
match value.int_value {
Some(v) => Ok((a, v as i32)),
None => Err(()),
}
}
_ => {
input.reset(start_position);
Ok((a, 0))
}
}
}.map_err(|()| ParseError::UnexpectedToken(token.unwrap()))
}

fn parse_signless_b(input: &mut Parser, a: i32, b_sign: i32) -> Result<(i32, i32), ()> {
match try!(input.next()) {
fn parse_signless_b<'i, 't>(input: &mut Parser<'i, 't>, a: i32, b_sign: i32) -> Result<(i32, i32), ParseError<'i>> {
let token = try!(input.next());
match token {
Token::Number(ref value) if !value.has_sign => {
Ok((a, b_sign * (try!(value.int_value.ok_or(())) as i32)))
match value.int_value {
Some(v) => Ok((a, b_sign * v as i32)),
None => Err(()),
}
}
_ => Err(())
}
}.map_err(|()| ParseError::UnexpectedToken(token))
}

fn parse_n_dash_digits(string: &str) -> Result<i32, ()> {
Expand Down
Loading