Discussion 5: A only - Enums and error handling practice
Paste this code into Rust Playground and complete the functions marked with todo!().
The discussion also used slides which are not available here.
#![allow(unused)] fn main() { // All legal values in a simple expression as enum variants #[derive(Debug, PartialEq, Clone, Copy)] enum Token { Num(f64), Plus, Minus, Slash, Star } impl Token { fn parse(self) -> Result<f64, ParseError> { if let Token::Num(x) = self { Ok(x) } else { Err(ParseError::UnexpectedToken(self)) } } } /// All possible errors /// /// *-----------------------* /// - UnexpectedToken: putting two operations together, putting two numbers together, etc. /// - InvalidInput: inputting any non-numerical value thats not an operation /// - TrailingInput: ending an expression without finishing an operation /// - DivisionByZero: dividing by zero /// - EmptyInput: evaluating an expression with nothing in it #[derive(Debug, PartialEq)] enum ParseError { UnexpectedToken(Token), InvalidInput(String), TrailingInput, DivisionByZero, EmptyInput, } // Helper that turns any string into a list, splitting on whitespace fn into_array(input: &str) -> Vec<&str> { input.split_whitespace().collect() } // Helper that reads its input string as a number, rejecting non-finite values like "inf" and "NaN" fn parse_number(input: &str) -> Option<f64> { input.parse::<f64>().ok().filter(|n| n.is_finite()) } /// Create a vector array to hold tokens, then parse the string delimited by spaces to tokenize /// the expression into an executable form fn parse_line(input: &str) -> Result<Vec<Token>, ParseError>{ let mut tokens: Vec<Token> = Vec::new(); let expr: Vec<&str> = into_array(input); todo!() } /// Evaluate the expression. Consider edge cases: what happens when the expression is of length 1? fn eval(input: Vec<Token>) -> Result<f64, ParseError>{ // This consumes our input and turns it into a mutable collection let mut expr = input.into_iter(); // This sets value to expr[0] then pops that value, turns it from Some() -> Result(), unwraps it, then parses it // with Token::parse() before unwrapping it again. We get the number out of the token and raise the relevant // error otherwise. let mut value: f64 = expr.next().ok_or(ParseError::EmptyInput)?.parse()?; todo!() } #[cfg(test)] mod tests { use super::*; // Helper that runs a full line through the tokenizer and the evaluator fn calc(input: &str) -> Result<f64, ParseError> { parse_line(input).and_then(eval) } // ---------- parse_line ---------- #[test] fn parse_line_tokenizes_numbers_and_operations() { assert_eq!( parse_line("1 + 2 - 3 * 4 / 5"), Ok(vec![ Token::Num(1.0), Token::Plus, Token::Num(2.0), Token::Minus, Token::Num(3.0), Token::Star, Token::Num(4.0), Token::Slash, Token::Num(5.0) ]) ); } #[test] fn parse_line_handles_decimals_and_negative_numbers() { assert_eq!( parse_line("-2.5 + 0.25"), Ok(vec![Token::Num(-2.5), Token::Plus, Token::Num(0.25)]) ); } #[test] fn parse_line_ignores_extra_whitespace() { assert_eq!( parse_line(" 1 +\t2 "), Ok(vec![Token::Num(1.0), Token::Plus, Token::Num(2.0)]) ); } #[test] fn parse_line_empty_string_gives_no_tokens() { assert_eq!(parse_line(""), Ok(vec![])); assert_eq!(parse_line(" "), Ok(vec![])); } #[test] fn parse_line_rejects_non_numeric_input() { assert_eq!(parse_line("1 + x"), Err(ParseError::InvalidInput("x".to_string()))); assert_eq!(parse_line("( 1 + 2 )"), Err(ParseError::InvalidInput("(".to_string()))); } #[test] fn parse_line_requires_spaces_between_tokens() { assert_eq!(parse_line("1+2"), Err(ParseError::InvalidInput("1+2".to_string()))); } #[test] fn parse_line_rejects_non_finite_numbers() { assert_eq!(parse_line("inf"), Err(ParseError::InvalidInput("inf".to_string()))); assert_eq!(parse_line("NaN"), Err(ParseError::InvalidInput("NaN".to_string()))); assert_eq!(parse_line("1e999"), Err(ParseError::InvalidInput("1e999".to_string()))); } // ---------- eval ---------- #[test] fn eval_single_number() { assert_eq!(calc("5"), Ok(5.0)); } #[test] fn eval_each_operation() { assert_eq!(calc("1 + 2"), Ok(3.0)); assert_eq!(calc("5 - 8"), Ok(-3.0)); assert_eq!(calc("4 * 2.5"), Ok(10.0)); assert_eq!(calc("9 / 4"), Ok(2.25)); } #[test] fn eval_goes_left_to_right_without_order_of_operations() { // With order of operations these would be 7 and 5 assert_eq!(calc("1 + 2 * 3"), Ok(9.0)); assert_eq!(calc("8 - 2 / 2"), Ok(3.0)); } #[test] fn eval_long_expression() { assert_eq!(calc("10 / 4 - 0.5 * 3 + 1"), Ok(7.0)); } #[test] fn eval_negative_operand() { assert_eq!(calc("3 - -2"), Ok(5.0)); assert_eq!(calc("-3 * -2"), Ok(6.0)); } #[test] fn eval_empty_input() { assert_eq!(calc(""), Err(ParseError::EmptyInput)); assert_eq!(eval(vec![]), Err(ParseError::EmptyInput)); } #[test] fn eval_leading_operation() { assert_eq!(calc("+ 1"), Err(ParseError::UnexpectedToken(Token::Plus))); } #[test] fn eval_two_operations_in_a_row() { assert_eq!(calc("1 + * 2"), Err(ParseError::UnexpectedToken(Token::Star))); } #[test] fn eval_two_numbers_in_a_row() { assert_eq!(calc("1 2"), Err(ParseError::UnexpectedToken(Token::Num(2.0)))); assert_eq!(calc("1 + 2 3"), Err(ParseError::UnexpectedToken(Token::Num(3.0)))); } #[test] fn eval_trailing_operation() { assert_eq!(calc("1 +"), Err(ParseError::TrailingInput)); assert_eq!(calc("1 + 2 *"), Err(ParseError::TrailingInput)); } #[test] fn eval_division_by_zero() { assert_eq!(calc("4 / 0"), Err(ParseError::DivisionByZero)); assert_eq!(calc("4 / 0.0"), Err(ParseError::DivisionByZero)); assert_eq!(calc("4 / -0"), Err(ParseError::DivisionByZero)); } #[test] fn eval_zero_divided_by_number_is_fine() { assert_eq!(calc("0 / 4"), Ok(0.0)); } #[test] fn eval_stops_at_first_error() { // The division by zero comes before the trailing operation assert_eq!(calc("1 / 0 +"), Err(ParseError::DivisionByZero)); } } }