From 25d7c7573d4d70773c9b6e35b0206fc6b9e635e8 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Tue, 26 Oct 2021 12:08:26 -0700 Subject: [PATCH 1/2] Add tests of negative literal parsing --- tests/test.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/test.rs b/tests/test.rs index 64de3e2a..ab823907 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -168,7 +168,11 @@ fn literal_iter_negative() { #[test] fn literal_parse() { assert!("1".parse::().is_ok()); + assert!("-1".parse::().is_ok()); + assert!("-1u12".parse::().is_ok()); assert!("1.0".parse::().is_ok()); + assert!("-1.0".parse::().is_ok()); + assert!("-1.0f12".parse::().is_ok()); assert!("'a'".parse::().is_ok()); assert!("\"\n\"".parse::().is_ok()); assert!("0 1".parse::().is_err()); @@ -177,6 +181,9 @@ fn literal_parse() { assert!("/* comment */0".parse::().is_err()); assert!("0/* comment */".parse::().is_err()); assert!("0// comment".parse::().is_err()); + assert!("- 1".parse::().is_err()); + assert!("- 1.0".parse::().is_err()); + assert!("-\"\"".parse::().is_err()); } #[test] From 3f57d820f783a17992455fa4767dd39d05cb9e92 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Tue, 26 Oct 2021 12:11:24 -0700 Subject: [PATCH 2/2] Support negative int and float literals in FromStr --- src/fallback.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/fallback.rs b/src/fallback.rs index 3f8f5cb8..ce878b21 100644 --- a/src/fallback.rs +++ b/src/fallback.rs @@ -896,10 +896,20 @@ impl Literal { impl FromStr for Literal { type Err = LexError; - fn from_str(repr: &str) -> Result { + fn from_str(mut repr: &str) -> Result { + 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); } }