use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IntLiteralError {
Overflow,
}
pub(crate) fn parse_int_literal(s: &str) -> Result<i64, IntLiteralError> {
let (neg, digits) = match s.strip_prefix('-') {
Some(digits) => (true, digits),
None => (false, s),
};
let radix = match digits.as_bytes() {
[b'0', b'x', ..] => 16,
[b'0', b'o', ..] => 8,
_ => 0,
};
if radix == 0 {
return s.parse::<i64>().map_err(|_| IntLiteralError::Overflow);
}
let magnitude = &digits[2..];
let text = if neg {
format!("-{magnitude}")
} else {
magnitude.to_string()
};
i64::from_str_radix(&text, radix).map_err(|_| IntLiteralError::Overflow)
}
#[derive(Clone, Copy)]
pub(super) enum IntLiteralSite<'a> {
Expression,
Bounded { what: &'a str, max: u64 },
}
impl<'a> Parser<'a> {
pub(super) fn int_literal_error(
&self,
tok: &Token,
error: IntLiteralError,
site: IntLiteralSite<'_>,
) -> ParseError {
let IntLiteralError::Overflow = error;
match site {
IntLiteralSite::Expression => self
.error_at_token(tok, format!("integer overflow: {}", tok.literal))
.with_detail("IntegerOverflow"),
IntLiteralSite::Bounded { what, max } => self
.error_at_token(
tok,
format!(
"{what} out of range: {} exceeds the maximum of {max}",
tok.literal
),
)
.with_detail("IntegerOverflow"),
}
}
}