From a93fc48ee8a99a982976739892b4956f3d411b48 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Sat, 13 Nov 2021 13:33:15 -0800 Subject: [PATCH] Make anciliary parsing functions not panic --- schala-lang/language/src/parsing/new.rs | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/schala-lang/language/src/parsing/new.rs b/schala-lang/language/src/parsing/new.rs index 6ca0e04..134ef15 100644 --- a/schala-lang/language/src/parsing/new.rs +++ b/schala-lang/language/src/parsing/new.rs @@ -452,10 +452,10 @@ peg::parser! { digits:digits() { ExpressionKind::NatLiteral(digits.parse().unwrap()) } 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 = - "0x" digits:hex_digits() { ExpressionKind::NatLiteral(parse_hex(digits)) } + "0x" digits:hex_digits() {? parse_hex(digits).map(ExpressionKind::NatLiteral) } rule float_literal() -> ExpressionKind = 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 { let mut result: u64 = 0; let mut multiplier = 1; for d in digits.chars().rev() { @@ -483,17 +483,13 @@ fn parse_binary(digits: &str /*, tok: Token*/) -> u64 { } multiplier = match multiplier.checked_mul(2) { Some(m) => m, - None => - /*return ParseError::new_with_token("This binary expression will overflow", tok),*/ - panic!(), + None => return Err("Binary expression will overflow"), } } - //Ok(result) - result + Ok(result) } -//TODO fix these two functions -fn parse_hex(digits: &str) -> u64 { +fn parse_hex(digits: &str) -> Result { let mut result: u64 = 0; let mut multiplier: u64 = 1; for d in digits.chars().rev() { @@ -502,14 +498,14 @@ fn parse_hex(digits: &str) -> u64 { } match d.to_digit(16) { Some(n) => result += n as u64 * multiplier, - None => panic!(), + None => return Err("Internal parser error: invalid hex digit"), } multiplier = match multiplier.checked_mul(16) { Some(m) => m, - None => panic!(), + None => return Err("Hexadecimal expression will overflow"), } } - result + Ok(result) } #[derive(Debug)]