From 8b849016ba99e3bdfa74ecc0e6d5ac8bafc8c56a Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Sat, 16 Mar 2019 22:07:02 +0530 Subject: write basic AST structure --- src/main.rs | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index c9d02f7..6a97d1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,39 @@ #[derive(Debug)] -enum Token { +pub enum Token { Operator(char), Num(f64), - Paren(char) + 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)); + } + fn set_right(&mut self, val: Node) { + self.right = Box::new(Some(val)); + } } fn main() { - let input = "11(12)"; + let input = "11 + (1 + 2(3))"; let input = input.replace(" ", ""); let lexed = lexer(&input); @@ -23,29 +50,35 @@ fn lexer(input: &str) -> Result, String> { num_vec.push(letter); }, '+' | '-' | '/' | '*' | '^' => { + // parse num buf let parse_num = num_vec.parse::().ok(); if let Some(x) = parse_num { result.push(Token::Num(x)); num_vec.clear(); } - result.push(Token::Paren(letter)); + // finish + result.push(Token::Operator(letter)); }, '(' => { + // 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('*')); num_vec.clear(); } - result.push(Token::Paren(letter)); + // finish + result.push(Token::RParen); }, ')' => { + // parse num buf let parse_num = num_vec.parse::().ok(); if let Some(x) = parse_num { result.push(Token::Num(x)); num_vec.clear(); } - result.push(Token::Paren(letter)); + // finish + result.push(Token::LParen); } _ => { return Err(format!("Unexpected character: {}", letter)) @@ -54,3 +87,5 @@ fn lexer(input: &str) -> Result, String> { } Ok(result) } + + -- cgit v1.2.3