Make anciliary parsing functions not panic

This commit is contained in:
Greg Shuflin 2021-11-13 13:33:15 -08:00
parent 8fe7fca88c
commit a93fc48ee8

View File

@ -452,10 +452,10 @@ peg::parser! {
digits:digits() { ExpressionKind::NatLiteral(digits.parse().unwrap()) } digits:digits() { ExpressionKind::NatLiteral(digits.parse().unwrap()) }
rule bin_literal() -> ExpressionKind = rule bin_literal() -> ExpressionKind =
"0b" digits:bin_digits() { ExpressionKind::NatLiteral(parse_binary(digits)) } "0b" digits:bin_digits() {? parse_binary(digits).map(ExpressionKind::NatLiteral) }
rule hex_literal() -> ExpressionKind = rule hex_literal() -> ExpressionKind =
"0x" digits:hex_digits() { ExpressionKind::NatLiteral(parse_hex(digits)) } "0x" digits:hex_digits() {? parse_hex(digits).map(ExpressionKind::NatLiteral) }
rule float_literal() -> ExpressionKind = rule float_literal() -> ExpressionKind =
ds:$( digits() "." digits()? / "." digits() ) { ExpressionKind::FloatLiteral(ds.parse().unwrap()) } ds:$( digits() "." digits()? / "." digits() ) { ExpressionKind::FloatLiteral(ds.parse().unwrap()) }
@ -471,7 +471,7 @@ peg::parser! {
} }
} }
fn parse_binary(digits: &str /*, tok: Token*/) -> u64 { fn parse_binary(digits: &str) -> Result<u64, &'static str> {
let mut result: u64 = 0; let mut result: u64 = 0;
let mut multiplier = 1; let mut multiplier = 1;
for d in digits.chars().rev() { for d in digits.chars().rev() {
@ -483,17 +483,13 @@ fn parse_binary(digits: &str /*, tok: Token*/) -> u64 {
} }
multiplier = match multiplier.checked_mul(2) { multiplier = match multiplier.checked_mul(2) {
Some(m) => m, Some(m) => m,
None => None => return Err("Binary expression will overflow"),
/*return ParseError::new_with_token("This binary expression will overflow", tok),*/
panic!(),
} }
} }
//Ok(result) Ok(result)
result
} }
//TODO fix these two functions fn parse_hex(digits: &str) -> Result<u64, &'static str> {
fn parse_hex(digits: &str) -> u64 {
let mut result: u64 = 0; let mut result: u64 = 0;
let mut multiplier: u64 = 1; let mut multiplier: u64 = 1;
for d in digits.chars().rev() { for d in digits.chars().rev() {
@ -502,14 +498,14 @@ fn parse_hex(digits: &str) -> u64 {
} }
match d.to_digit(16) { match d.to_digit(16) {
Some(n) => result += n as u64 * multiplier, Some(n) => result += n as u64 * multiplier,
None => panic!(), None => return Err("Internal parser error: invalid hex digit"),
} }
multiplier = match multiplier.checked_mul(16) { multiplier = match multiplier.checked_mul(16) {
Some(m) => m, Some(m) => m,
None => panic!(), None => return Err("Hexadecimal expression will overflow"),
} }
} }
result Ok(result)
} }
#[derive(Debug)] #[derive(Debug)]