From a5238794efce5767139d9c4dbdf056bb859921d1 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Fri, 22 Mar 2019 19:26:47 +0530 Subject: support unary operators (minus and plus) --- src/lex/mod.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) (limited to 'src/lex') diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 7fd5e33..47e35b0 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -71,15 +71,31 @@ pub fn lexer(input: &str) -> Result, String> { } char_vec.push(letter); }, - '+' | '-' | '/' | '*' | '^' => { + '+' | '-' => { + let op_token = match letter { + '+' => Operator::token_from_op('+', |x, y| x + y, 2, true), + '-' => Operator::token_from_op('-', |x, y| x - y, 2, true), + _ => unreachable!() + }; + let parse_num = num_vec.parse::().ok(); + if let Some(x) = parse_num { + result.push(Token::Num(x)); + num_vec.clear(); + result.push(op_token); + } else { + result.push(Token::LParen); + result.push(Token::Num((letter.to_string() + "1").parse::().unwrap())); + result.push(Token::RParen); + result.push(Operator::token_from_op('*', |x, y| x * y, 2, true)); + } + }, + '/' | '*' | '^' => { let parse_num = num_vec.parse::().ok(); if let Some(x) = parse_num { result.push(Token::Num(x)); num_vec.clear(); } let operator_token: Token = match letter { - '+' => Operator::token_from_op('+', |x, y| x + y, 2, true), - '-' => Operator::token_from_op('-', |x, y| x - y, 2, true), '/' => Operator::token_from_op('/', |x, y| x / y, 3, true), '*' => Operator::token_from_op('*', |x, y| x * y, 3, true), '^' => Operator::token_from_op('^', |x, y| x.powf(y), 4, false), -- cgit v1.2.3