From f37b73df5d57232daec09e8aba126d292ada45f1 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Mon, 18 Mar 2019 21:59:05 +0530 Subject: new operator struct, updated lexer --- src/main.rs | 68 ++++++++++++++++++++++++++++++++----------------------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6a97d1c..c91b662 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,44 +1,41 @@ +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct Operator { + token: char, + operation: fn(f64, f64) -> f64, + precedence: u8, + is_left_associative: bool, +} + #[derive(Debug)] pub enum Token { - Operator(char), + Operator(Operator), Num(f64), LParen, RParen } -#[derive(Debug)] -pub struct Node { - value: Option, - left: Box>, - right: Box> -} - -impl Node { - fn new() -> Node { - Node { - value: None, - left: Box::new(None), - right: Box::new(None) - } - } - fn set_val(&mut self, val: Token) { - self.value = Some(val); - } - fn set_left(&mut self, val: Node) { - self.left = Box::new(Some(val)); +impl Operator { + fn token_from_op(token: char, operation: fn(f64, f64) -> f64, precedence: u8, is_left_associative: bool) -> Token { + Token::Operator( + Operator { + token, + operation, + precedence, + is_left_associative + } + ) } - fn set_right(&mut self, val: Node) { - self.right = Box::new(Some(val)); + fn operate(self, x: f64, y: f64) -> f64 { + (self.operation)(x, y) } } fn main() { - let input = "11 + (1 + 2(3))"; + let input = "1(2)"; let input = input.replace(" ", ""); - let lexed = lexer(&input); - println!("{:?}", lexed); + println!("{}", lexed.unwrap().len()); } fn lexer(input: &str) -> Result, String> { @@ -57,18 +54,26 @@ fn lexer(input: &str) -> Result, String> { num_vec.clear(); } // finish - result.push(Token::Operator(letter)); + 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), + _ => panic!("unexpected op whuuu"), + }; + result.push(operator_token); }, '(' => { // parse num buf let parse_num = num_vec.parse::().ok(); if let Some(x) = parse_num { result.push(Token::Num(x)); - result.push(Token::Operator('*')); + result.push(Operator::token_from_op('*', |x, y| x * y, 3, true)); num_vec.clear(); } // finish - result.push(Token::RParen); + result.push(Token::LParen); }, ')' => { // parse num buf @@ -78,8 +83,9 @@ fn lexer(input: &str) -> Result, String> { num_vec.clear(); } // finish - result.push(Token::LParen); + result.push(Token::RParen); } + ' ' => {} _ => { return Err(format!("Unexpected character: {}", letter)) } @@ -87,5 +93,3 @@ fn lexer(input: &str) -> Result, String> { } Ok(result) } - - -- cgit v1.2.3