aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/main.rs47
1 files changed, 41 insertions, 6 deletions
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 @@
1#[derive(Debug)] 1#[derive(Debug)]
2enum Token { 2pub enum Token {
3 Operator(char), 3 Operator(char),
4 Num(f64), 4 Num(f64),
5 Paren(char) 5 LParen,
6 RParen
7}
8
9#[derive(Debug)]
10pub struct Node {
11 value: Option<Token>,
12 left: Box<Option<Node>>,
13 right: Box<Option<Node>>
14}
15
16impl Node {
17 fn new() -> Node {
18 Node {
19 value: None,
20 left: Box::new(None),
21 right: Box::new(None)
22 }
23 }
24 fn set_val(&mut self, val: Token) {
25 self.value = Some(val);
26 }
27 fn set_left(&mut self, val: Node) {
28 self.left = Box::new(Some(val));
29 }
30 fn set_right(&mut self, val: Node) {
31 self.right = Box::new(Some(val));
32 }
6} 33}
7 34
8fn main() { 35fn main() {
9 let input = "11(12)"; 36 let input = "11 + (1 + 2(3))";
10 let input = input.replace(" ", ""); 37 let input = input.replace(" ", "");
11 38
12 let lexed = lexer(&input); 39 let lexed = lexer(&input);
@@ -23,29 +50,35 @@ fn lexer(input: &str) -> Result<Vec<Token>, String> {
23 num_vec.push(letter); 50 num_vec.push(letter);
24 }, 51 },
25 '+' | '-' | '/' | '*' | '^' => { 52 '+' | '-' | '/' | '*' | '^' => {
53 // parse num buf
26 let parse_num = num_vec.parse::<f64>().ok(); 54 let parse_num = num_vec.parse::<f64>().ok();
27 if let Some(x) = parse_num { 55 if let Some(x) = parse_num {
28 result.push(Token::Num(x)); 56 result.push(Token::Num(x));
29 num_vec.clear(); 57 num_vec.clear();
30 } 58 }
31 result.push(Token::Paren(letter)); 59 // finish
60 result.push(Token::Operator(letter));
32 }, 61 },
33 '(' => { 62 '(' => {
63 // parse num buf
34 let parse_num = num_vec.parse::<f64>().ok(); 64 let parse_num = num_vec.parse::<f64>().ok();
35 if let Some(x) = parse_num { 65 if let Some(x) = parse_num {
36 result.push(Token::Num(x)); 66 result.push(Token::Num(x));
37 result.push(Token::Operator('*')); 67 result.push(Token::Operator('*'));
38 num_vec.clear(); 68 num_vec.clear();
39 } 69 }
40 result.push(Token::Paren(letter)); 70 // finish
71 result.push(Token::RParen);
41 }, 72 },
42 ')' => { 73 ')' => {
74 // parse num buf
43 let parse_num = num_vec.parse::<f64>().ok(); 75 let parse_num = num_vec.parse::<f64>().ok();
44 if let Some(x) = parse_num { 76 if let Some(x) = parse_num {
45 result.push(Token::Num(x)); 77 result.push(Token::Num(x));
46 num_vec.clear(); 78 num_vec.clear();
47 } 79 }
48 result.push(Token::Paren(letter)); 80 // finish
81 result.push(Token::LParen);
49 } 82 }
50 _ => { 83 _ => {
51 return Err(format!("Unexpected character: {}", letter)) 84 return Err(format!("Unexpected character: {}", letter))
@@ -54,3 +87,5 @@ fn lexer(input: &str) -> Result<Vec<Token>, String> {
54 } 87 }
55 Ok(result) 88 Ok(result)
56} 89}
90
91