aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 6a97d1c637c52320ec7cab288b583af9be3c6a92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#[derive(Debug)]
pub enum Token {
    Operator(char),
    Num(f64),
    LParen,
    RParen
}

#[derive(Debug)]
pub struct Node {
    value: Option<Token>,
    left: Box<Option<Node>>,
    right: Box<Option<Node>>
}

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 + (1 + 2(3))";
    let input = input.replace(" ", "");

    let lexed = lexer(&input);

    println!("{:?}", lexed);
}

fn lexer(input: &str) -> Result<Vec<Token>, String> {
    let mut num_vec: String = String::new();
    let mut result: Vec<Token> = vec![];
    for letter in input.chars() {
        match letter {
            '0'...'9' | '.' => {
                num_vec.push(letter);
            },
            '+' | '-' | '/' | '*' | '^' => {
                // parse num buf
                let parse_num = num_vec.parse::<f64>().ok();
                if let Some(x) = parse_num {
                    result.push(Token::Num(x));
                    num_vec.clear();
                }
                // finish
                result.push(Token::Operator(letter));
            },
            '('  => {
                // parse num buf
                let parse_num = num_vec.parse::<f64>().ok();
                if let Some(x) = parse_num {
                    result.push(Token::Num(x));
                    result.push(Token::Operator('*'));
                    num_vec.clear();
                }
                // finish
                result.push(Token::RParen);
            },
            ')' => {
                // parse num buf
                let parse_num = num_vec.parse::<f64>().ok();
                if let Some(x) = parse_num {
                    result.push(Token::Num(x));
                    num_vec.clear();
                }
                // finish
                result.push(Token::LParen);
            }
            _ => {
                return Err(format!("Unexpected character: {}", letter))
            }
        }
    }
    Ok(result)
}