Skip to content

Commit

Permalink
Merge pull request #301 from dtolnay/negative
Browse files Browse the repository at this point in the history
Support negative int and float literals in FromStr
  • Loading branch information
dtolnay committed Oct 26, 2021
2 parents 37484ec + 3f57d82 commit 4178471
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/fallback.rs
Expand Up @@ -896,10 +896,20 @@ impl Literal {
impl FromStr for Literal {
type Err = LexError;

fn from_str(repr: &str) -> Result<Self, Self::Err> {
fn from_str(mut repr: &str) -> Result<Self, Self::Err> {
let negative = repr.starts_with('-');
if negative {
repr = &repr[1..];
if !repr.starts_with(|ch: char| ch.is_ascii_digit()) {
return Err(LexError::call_site());
}
}
let cursor = get_cursor(repr);
if let Ok((_rest, literal)) = parse::literal(cursor) {
if let Ok((_rest, mut literal)) = parse::literal(cursor) {
if literal.text.len() == repr.len() {
if negative {
literal.text.insert(0, '-');
}
return Ok(literal);
}
}
Expand Down
7 changes: 7 additions & 0 deletions tests/test.rs
Expand Up @@ -168,7 +168,11 @@ fn literal_iter_negative() {
#[test]
fn literal_parse() {
assert!("1".parse::<Literal>().is_ok());
assert!("-1".parse::<Literal>().is_ok());
assert!("-1u12".parse::<Literal>().is_ok());
assert!("1.0".parse::<Literal>().is_ok());
assert!("-1.0".parse::<Literal>().is_ok());
assert!("-1.0f12".parse::<Literal>().is_ok());
assert!("'a'".parse::<Literal>().is_ok());
assert!("\"\n\"".parse::<Literal>().is_ok());
assert!("0 1".parse::<Literal>().is_err());
Expand All @@ -177,6 +181,9 @@ fn literal_parse() {
assert!("/* comment */0".parse::<Literal>().is_err());
assert!("0/* comment */".parse::<Literal>().is_err());
assert!("0// comment".parse::<Literal>().is_err());
assert!("- 1".parse::<Literal>().is_err());
assert!("- 1.0".parse::<Literal>().is_err());
assert!("-\"\"".parse::<Literal>().is_err());
}

#[test]
Expand Down

0 comments on commit 4178471

Please sign in to comment.