diff options
Diffstat (limited to 'src/lex')
-rw-r--r-- | src/lex/mod.rs | 22 |
1 files changed, 20 insertions, 2 deletions
diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 5e7a346..cac16ca 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs | |||
@@ -122,7 +122,7 @@ fn factorial (n: f64) -> f64 { | |||
122 | n.signum() * (1.. n.abs() as u64 +1).fold(1, |p, n| p*n) as f64 | 122 | n.signum() * (1.. n.abs() as u64 +1).fold(1, |p, n| p*n) as f64 |
123 | } | 123 | } |
124 | 124 | ||
125 | pub fn lexer(input: &str) -> Result<Vec<Token>, CalcError> { | 125 | pub fn lexer(input: &str, prev_ans: &mut f64) -> Result<Vec<Token>, CalcError> { |
126 | let functions: HashMap<&str, Token> = get_functions(); | 126 | let functions: HashMap<&str, Token> = get_functions(); |
127 | let operators: HashMap<char, Token> = get_operators(); | 127 | let operators: HashMap<char, Token> = get_operators(); |
128 | 128 | ||
@@ -144,6 +144,23 @@ pub fn lexer(input: &str) -> Result<Vec<Token>, CalcError> { | |||
144 | num_vec.push(letter); | 144 | num_vec.push(letter); |
145 | last_char_is_op = false; | 145 | last_char_is_op = false; |
146 | }, | 146 | }, |
147 | '_' => { | ||
148 | if char_vec.len() > 0 { | ||
149 | if let Some(_) = functions.get(&char_vec[..]) { | ||
150 | return Err(CalcError::Syntax(format!("Function '{}' expected parentheses", char_vec))) | ||
151 | } else { | ||
152 | return Err(CalcError::Syntax(format!("Unexpected character '{}'", char_vec))) | ||
153 | } | ||
154 | } | ||
155 | let parse_num = num_vec.parse::<f64>().ok(); | ||
156 | if let Some(x) = parse_num { | ||
157 | result.push(Token::Num(x)); | ||
158 | result.push(operators.get(&'*').unwrap().clone()); | ||
159 | num_vec.clear(); | ||
160 | } | ||
161 | last_char_is_op = false; | ||
162 | result.push(Token::Num(*prev_ans)); | ||
163 | } | ||
147 | 'a'...'z' | 'A'...'Z' => { | 164 | 'a'...'z' | 'A'...'Z' => { |
148 | let parse_num = num_vec.parse::<f64>().ok(); | 165 | let parse_num = num_vec.parse::<f64>().ok(); |
149 | if let Some(x) = parse_num { | 166 | if let Some(x) = parse_num { |
@@ -216,10 +233,11 @@ pub fn lexer(input: &str) -> Result<Vec<Token>, CalcError> { | |||
216 | }, | 233 | }, |
217 | ' ' => {}, | 234 | ' ' => {}, |
218 | _ => { | 235 | _ => { |
219 | return Err(CalcError::Syntax(format!("Unexpected character: '{}'", letter))) | 236 | return Err(CalcError::Syntax(format!("Unexpected token: '{}'", letter))) |
220 | } | 237 | } |
221 | } | 238 | } |
222 | } | 239 | } |
240 | // println!("{:?}", result); | ||
223 | drain_num_stack(&mut num_vec, &mut result); | 241 | drain_num_stack(&mut num_vec, &mut result); |
224 | Ok(result) | 242 | Ok(result) |
225 | } | 243 | } |