From 5af8b2df43f33e5d0b12398ffa6ad9d51a2a97ff Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Sat, 23 Mar 2019 14:52:27 +0530 Subject: handle unreachable match cases, error handling --- src/parse/mod.rs | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/parse/mod.rs b/src/parse/mod.rs index e5c28e6..4238e3b 100644 --- a/src/parse/mod.rs +++ b/src/parse/mod.rs @@ -1,6 +1,7 @@ use crate::lex::Token; +use crate::error::CalcError; -pub fn to_postfix(tokens: Vec) -> Result, String> { +pub fn to_postfix(tokens: Vec) -> Result, CalcError> { let mut postfixed: Vec = vec![]; let mut op_stack: Vec = vec![]; for token in tokens { @@ -29,9 +30,7 @@ pub fn to_postfix(tokens: Vec) -> Result, String> { Token::Function(_) => { postfixed.push(op_stack.pop().unwrap()); } - _ => { - return Err(format!("{:?} must not be on operator stack", top_op)) - } + _ => { unreachable!(); } } } op_stack.push(token); @@ -49,7 +48,7 @@ pub fn to_postfix(tokens: Vec) -> Result, String> { postfixed.push(token) } if !push_until_paren { - return Err(String::from("Mismatched ')'")); + return Err(CalcError::Syntax("Mismatched parentheses!".into())); } } } @@ -60,7 +59,7 @@ pub fn to_postfix(tokens: Vec) -> Result, String> { Ok(postfixed) } -pub fn eval_postfix(postfixed: Vec) -> Result { +pub fn eval_postfix(postfixed: Vec) -> Result { let mut num_stack: Vec = vec![]; for token in postfixed { match token { @@ -70,27 +69,39 @@ pub fn eval_postfix(postfixed: Vec) -> Result { Token::Operator(op) => { if let Some(n2) = num_stack.pop() { if let Some(n1) = num_stack.pop() { - num_stack.push(op.operate(n1, n2)) + num_stack.push(op.operate(n1, n2)?); } else { - return Err(format!("Too many operators, Too little operands")) + return Err( + CalcError::Parser( + format!("Too many operators, Too little operands") + ) + ) } } else { - return Err(format!("Too many operators, Too little operands")) + return Err( + CalcError::Parser( + format!("Too many operators, Too little operands") + ) + ) } }, Token::Function(funct) => { if let Some(arg) = num_stack.pop() { - num_stack.push(funct.apply(arg)) + num_stack.push(funct.apply(arg)?) } } _ => { - return Err(format!("Yo nibba how did this get here")) + unreachable!("nah nigga") } } } if num_stack.len() == 1 { Ok(num_stack.pop().unwrap()) } else { - Err(format!("Parser Error")) + return Err( + CalcError::Parser( + format!("Too many operators, Too little operands") + ) + ) } } -- cgit v1.2.3