aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 02473ae12feeb3085488b5681db38fe346486004 (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
use std::str;

#[derive(Debug)]
struct Token {
    kind: String,
    val: String,
}

fn main() {
    let input: &str = "2y + 11 ^ x";
    let input = input.replace(" ", "");
    println!("{}", input);

    let mut num_vec: String = String::new();
    let mut char_vec: String = String::new();

    let mut result: Vec<Token> = vec![];

    for letter in input.chars() {
        if letter.is_digit(10) {
            num_vec.push(letter);
        } else if letter == '.' {
            num_vec.push(letter);
        } else if letter.is_alphabetic() {
            let literal = buffer_to_token("Literal", &num_vec[..]);
            if let Some(x) = literal {
                result.push(x);
            }
            char_vec.push(letter);
            num_vec.clear();
        } else if is_operator(letter) {
            let literal = buffer_to_token("Literal", &num_vec[..]);
            let variable = buffer_to_token("Variable", &char_vec[..]);
            if let Some(x) = literal {
                result.push(x);
            }
            if let Some(x) = variable {
                result.push(x);
            }
            num_vec.clear();
            char_vec.clear();
            result.push(Token { kind: "Operator".into(), val: letter.to_string() });
        }
        println!("{}", letter);
        for token in &result {
            println!("{:?}", token);
        }
    }
}

fn buffer_to_token(k: &str, v: &str) -> Option<Token> {
    if v.len() > 0 {
        let token = Token {
            kind: k.into(),
            val: v.chars().collect::<String>()
        };
        Some(token)
    } else {
        None
    }
}

fn is_operator(x: char) -> bool {
    match x {
        '+' | '-' | '/' | '*' | '^' => true,
        _ => false
    }
}