Skip to content
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

Carry index of InvalidDigit on IntErrorKind #79728

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/middle/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn update_limit(
let error_str = match e.kind() {
IntErrorKind::PosOverflow => "`limit` is too large",
IntErrorKind::Empty => "`limit` must be a non-negative integer",
IntErrorKind::InvalidDigit => "not a valid integer",
IntErrorKind::InvalidDigit(_) => "not a valid integer",
IntErrorKind::NegOverflow => {
bug!("`limit` should never negatively overflow")
}
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/iter/traits/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1588,7 +1588,7 @@ pub trait Iterator {
/// This will print:
///
/// ```text
/// Parsing error: invalid digit found in string
/// Parsing error: invalid digit found at index 0
/// Sum: 3
/// ```
#[inline]
Expand Down
13 changes: 9 additions & 4 deletions library/core/src/num/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,14 @@ pub enum IntErrorKind {
///
/// Among other causes, this variant will be constructed when parsing an empty string.
Empty,
/// Contains an invalid digit in its context.
/// Contains an invalid digit at the index provided.
///
/// Among other causes, this variant will be constructed when parsing a string that
/// contains a non-ASCII char.
///
/// This variant is also constructed when a `+` or `-` is misplaced within a string
/// either on its own or in the middle of a number.
InvalidDigit,
InvalidDigit(usize),
/// Integer is too large to store in target integer type.
PosOverflow,
/// Integer is too small to store in target integer type.
Expand Down Expand Up @@ -135,7 +135,7 @@ impl ParseIntError {
pub fn __description(&self) -> &str {
match self.kind {
IntErrorKind::Empty => "cannot parse integer from empty string",
IntErrorKind::InvalidDigit => "invalid digit found in string",
IntErrorKind::InvalidDigit(_) => "invalid digit found in string",
IntErrorKind::PosOverflow => "number too large to fit in target type",
IntErrorKind::NegOverflow => "number too small to fit in target type",
IntErrorKind::Zero => "number would be zero for non-zero type",
Expand All @@ -146,6 +146,11 @@ impl ParseIntError {
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Display for ParseIntError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.__description().fmt(f)
match self.kind {
IntErrorKind::InvalidDigit(i) => {
write!(f, "invalid digit found at index {}", i)
}
_ => self.__description().fmt(f),
}
}
}
35 changes: 20 additions & 15 deletions library/core/src/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -824,34 +824,39 @@ fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, Par
radix
);

if src.is_empty() {
return Err(PIE { kind: Empty });
}

let is_signed_ty = T::from_u32(0) > T::min_value();

// all valid digits are ascii, so we will just iterate over the utf8 bytes
// and cast them to chars. .to_digit() will safely return None for anything
// other than a valid ascii digit for the given radix, including the first-byte
// of multi-byte sequences
let src = src.as_bytes();

let (is_positive, digits) = match src[0] {
b'+' | b'-' if src[1..].is_empty() => {
return Err(PIE { kind: InvalidDigit });
let mut src = src.as_bytes().iter().enumerate().peekable();

let first_digit = src.peek().ok_or(PIE { kind: Empty })?.1;

let (is_positive, digits) = match first_digit {
b'+' | b'-' => {
src.next();
if src.peek().is_none() {
return Err(PIE { kind: InvalidDigit(0) });
eopb marked this conversation as resolved.
Show resolved Hide resolved
} else {
match first_digit {
b'+' => (true, src),
b'-' if is_signed_ty => (false, src),
_ => return Err(PIE { kind: InvalidDigit(0) }),
}
}
}
b'+' => (true, &src[1..]),
b'-' if is_signed_ty => (false, &src[1..]),
_ => (true, src),
};

let mut result = T::from_u32(0);
if is_positive {
// The number is positive
for &c in digits {
for (index, &c) in digits {
let x = match (c as char).to_digit(radix) {
Some(x) => x,
None => return Err(PIE { kind: InvalidDigit }),
None => return Err(PIE { kind: InvalidDigit(index) }),
};
result = match result.checked_mul(radix) {
Some(result) => result,
Expand All @@ -864,10 +869,10 @@ fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, Par
}
} else {
// The number is negative
for &c in digits {
for (index, &c) in digits {
let x = match (c as char).to_digit(radix) {
Some(x) => x,
None => return Err(PIE { kind: InvalidDigit }),
None => return Err(PIE { kind: InvalidDigit(index) }),
};
result = match result.checked_mul(radix) {
Some(result) => result,
Expand Down
2 changes: 1 addition & 1 deletion library/core/tests/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ fn test_from_str() {
assert_eq!("0".parse::<NonZeroU8>().err().map(|e| e.kind().clone()), Some(IntErrorKind::Zero));
assert_eq!(
"-1".parse::<NonZeroU8>().err().map(|e| e.kind().clone()),
Some(IntErrorKind::InvalidDigit)
Some(IntErrorKind::InvalidDigit(0))
);
assert_eq!(
"-129".parse::<NonZeroI8>().err().map(|e| e.kind().clone()),
Expand Down
16 changes: 8 additions & 8 deletions library/core/tests/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,14 @@ fn test_leading_plus() {

#[test]
fn test_invalid() {
test_parse::<i8>("--129", Err(IntErrorKind::InvalidDigit));
test_parse::<i8>("++129", Err(IntErrorKind::InvalidDigit));
test_parse::<u8>("Съешь", Err(IntErrorKind::InvalidDigit));
test_parse::<u8>("123Hello", Err(IntErrorKind::InvalidDigit));
test_parse::<i8>("--", Err(IntErrorKind::InvalidDigit));
test_parse::<i8>("-", Err(IntErrorKind::InvalidDigit));
test_parse::<i8>("+", Err(IntErrorKind::InvalidDigit));
test_parse::<u8>("-1", Err(IntErrorKind::InvalidDigit));
test_parse::<i8>("--129", Err(IntErrorKind::InvalidDigit(1)));
test_parse::<i8>("++129", Err(IntErrorKind::InvalidDigit(1)));
test_parse::<u8>("Съешь", Err(IntErrorKind::InvalidDigit(0)));
test_parse::<u8>("123Hello", Err(IntErrorKind::InvalidDigit(3)));
test_parse::<i8>("--", Err(IntErrorKind::InvalidDigit(1)));
test_parse::<i8>("-", Err(IntErrorKind::InvalidDigit(0)));
test_parse::<i8>("+", Err(IntErrorKind::InvalidDigit(0)));
test_parse::<u8>("-1", Err(IntErrorKind::InvalidDigit(0)));
}

#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ error[E0545]: `issue` must be a non-zero numeric string or "none"
LL | #[unstable(feature = "unstable_test_feature", issue = "something")]
| ^^^^^^^^-----------
| |
| invalid digit found in string
| invalid digit found at index 0

error: aborting due to 2 previous errors

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ error[E0545]: `issue` must be a non-zero numeric string or "none"
LL | #[unstable(feature = "a", issue = "no")]
| ^^^^^^^^----
| |
| invalid digit found in string
| invalid digit found at index 0

error: aborting due to 3 previous errors

Expand Down