From a532676b17af062f403a2eac4299e2ba295e51b7 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Sun, 24 Feb 2019 12:49:18 +0530 Subject: refactor --- src/main.rs | 46 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 0a13e3e..02473ae 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,17 +1,18 @@ use std::str; +#[derive(Debug)] struct Token { kind: String, val: String, } fn main() { - let input: &str = "2y + 11 + sin(5)"; + let input: &str = "2y + 11 ^ x"; let input = input.replace(" ", ""); println!("{}", input); - let mut num_vec: Vec = vec![]; - let mut char_vec: Vec = vec![]; + let mut num_vec: String = String::new(); + let mut char_vec: String = String::new(); let mut result: Vec = vec![]; @@ -21,19 +22,42 @@ fn main() { } else if letter == '.' { num_vec.push(letter); } else if letter.is_alphabetic() { - if num_vec.len() > 0 { - let token = Token { - kind: "Literal".into(), - val: num_vec.iter().collect::() - }; - result.push(token); - char_vec.push(letter); + 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 { + if v.len() > 0 { + let token = Token { + kind: k.into(), + val: v.chars().collect::() + }; + Some(token) + } else { + None + } } fn is_operator(x: char) -> bool { -- cgit v1.2.3