1#![doc = include_str!("../README.md")]
2
3pub mod error;
4use error::{CalcError, Res};
5#[derive(pest_derive::Parser)]
6#[grammar = "grammar.pest"]
7pub struct ParserCalculator;
8
9pub fn pars(input: &str) -> Res<i32> {
22 if input.trim().is_empty() {
23 return Err(CalcError::EmptyExp);
24 }
25 let input = input.trim();
26 check_bracket(&input.to_string())
27}
28
29pub fn check_bracket(input: &String) -> Res<i32> {
32 if input.contains("pow") {
33 return to_power(input);
34 }
35 if input.contains("sqrt") {
36 return to_sqrt(input);
37 }
38 if input.contains("sin") {
39 return sin_func(input);
40 }
41 if input.contains("cos") {
42 return cos_func(input);
43 }
44 if input.contains("!") && input.contains('(') && input.contains(')') {
45 return fac_func(input);
46 }
47 let mut new_input = input.clone();
48 while new_input.contains('(') && new_input.contains(')') {
49 let input_chars: Vec<char> = new_input.chars().collect();
50 let mut open_bracket: Option<usize> = None;
51 let mut close_bracket: Option<usize> = None;
52
53 for (a, &c) in input_chars.iter().enumerate() {
54 if c == '(' {
55 open_bracket = Some(a);
56 } else if c == ')' && open_bracket.is_some() {
57 close_bracket = Some(a);
58 break;
59 }
60 }
61 if open_bracket.is_none() || close_bracket.is_none() {
62 return Err(CalcError::NoBracket);
63 }
64
65 let index_start = open_bracket.unwrap();
66 let index_end = close_bracket.unwrap();
67 let in_bracket = input_chars[index_start + 1..index_end].iter().collect();
68
69 let num_in_bracket = parse_number(&in_bracket);
70 let sign_in_bracket = parse_sign(&in_bracket);
71 let value_bracket = calc(num_in_bracket, sign_in_bracket)?;
72
73 new_input.replace_range(index_start..=index_end, &value_bracket.to_string());
74 }
75 let number_input: Vec<i32> = parse_number(&new_input);
76 let sign_input: Vec<char> = parse_sign(&new_input);
77
78 calc(number_input, sign_input)
79}
80
81pub fn parse_number(input: &String) -> Vec<i32> {
86 let number: Vec<i32> = input
87 .replace("+", " ")
88 .replace("-", " ")
89 .replace("*", " ")
90 .replace("/", " ")
91 .split_whitespace()
92 .filter_map(|n| n.parse::<i32>().ok())
93 .collect();
94 println!("{:?}", number);
95 number
96}
97
98pub fn parse_sign(input: &String) -> Vec<char> {
104 let ch: Vec<char> = input
105 .chars()
106 .filter(|c| *c == '+' || *c == '-' || *c == '*' || *c == '/')
107 .collect();
108
109 println!("{:?}", ch);
110 ch
111}
112
113pub fn calc(mut number: Vec<i32>, mut ch: Vec<char>) -> Res<i32> {
119 if number.is_empty() {
120 return Err(CalcError::EmptyExp);
121 }
122 let mut b = 0;
123 while b < ch.len() {
124 if b + 1 >= number.len() {
125 break;
126 }
127 if ch[b] == '*' {
128 number[b] *= number[b + 1];
129 number.remove(b + 1);
130 ch.remove(b);
131 } else if ch[b] == '/' {
132 if number[b + 1] == 0 {
133 return Err(CalcError::DivByZero);
134 }
135 number[b] /= number[b + 1];
136 number.remove(b + 1);
137 ch.remove(b);
138 } else {
139 b += 1;
140 }
141 }
142
143 let mut res = number[0];
144 for a in 0..ch.len() {
145 if a + 1 >= number.len() {
146 break;
147 }
148 if ch[a] == '+' {
149 res += number[a + 1];
150 } else if ch[a] == '-' {
151 res -= number[a + 1];
152 }
153 }
154
155 Ok(res)
156}
157
158pub fn to_power(input: &String) -> Res<i32> {
159 let mut res: i32 = 1;
160 let replace_input: String = input.replace("pow(", "").replace(")", "");
161 if replace_input.is_empty() {
162 return Err(CalcError::EmptyExp);
163 }
164 let numbers: Vec<i32> = replace_input
165 .replace(",", " ")
166 .split(" ")
167 .map(|s| s.parse().unwrap())
168 .collect();
169 let number = numbers[0];
170 let power = numbers[1];
171 for _ in 0..power as usize {
172 res *= number;
173 }
174 Ok(res)
175}
176
177pub fn to_sqrt(input: &String) -> Res<i32> {
178 let replcae_input: String = input.replace("sqrt(", "").replace(")", "");
179
180 if replcae_input.is_empty() {
181 return Err(CalcError::EmptyExp);
182 }
183 let number = replcae_input.parse().unwrap();
184 let mut res: i32 = 0;
185 for i in 1..number {
186 if i * i == number {
187 res = i;
188 break;
189 }
190 }
191 Ok(res)
192}
193
194pub fn sin_func(input: &String) -> Res<i32> {
195 let num = input.replace("sin(", "").replace(")", "");
196 let num: f64 = num.parse().unwrap();
197 Ok(num.to_radians().sin().round() as i32)
198}
199
200pub fn cos_func(input: &String) -> Res<i32> {
201 let num = input.replace("cos(", "").replace(")", "");
202 let num: f64 = num.parse().unwrap();
203 Ok(num.to_radians().cos().round() as i32)
204}
205
206pub fn fac_func(input: &String) -> Res<i32> {
207 if input.is_empty() {
208 return Err(CalcError::EmptyExp);
209 }
210 let mut res = 1;
211 let mut count = 0;
212 for i in input.chars() {
213 if i == '!' {
214 count += 1;
215 }
216 }
217 if count == 1 {
218 let num = input.replace("!", "");
219 let num: i32 = if num.contains('(') || num.contains('+') || num.contains('-') {
220 check_bracket(&num)?
221 } else {
222 num.parse().map_err(|_| CalcError::InvalidInput)?
223 };
224 for i in 1..=num {
225 res *= i;
226 }
227 } else if count == 2 {
228 let num = input.replace("(", "").replace("!", "").replace(")", "");
229 let num: i32 = if num.contains('(') || num.contains('+') || num.contains('-') {
230 check_bracket(&num)?
231 } else {
232 num.parse().map_err(|_| CalcError::InvalidInput)?
233 };
234
235 for i in 1..=num {
236 res *= i;
237 }
238 let temp = res;
239 res = 1;
240 for i in 1..=temp {
241 res *= i;
242 }
243 } else {
244 return Err(CalcError::InvalidInput);
245 }
246
247 Ok(res)
248}
249
250#[cfg(test)]
251mod tests {
252 use super::*;
253 #[test]
254 fn test_number_one() {
255 assert_eq!(check_bracket(&"12+(3*1)*2".to_string()).unwrap(), 18);
256 }
257
258 #[test]
259 fn test_number_two() {
260 assert_eq!(check_bracket(&"(2+3)*5-25".to_string()).unwrap(), 0);
261 }
262
263 #[test]
264
265 fn test_number_three() {
266 assert_eq!(check_bracket(&"2*(2*(2*2))".to_string()).unwrap(), 16);
267 }
268
269 #[test]
270
271 fn test_number_four() {
272 assert_eq!(
273 check_bracket(&"200+200+100*(100+100)-(100-90)".to_string()).unwrap(),
274 20390
275 );
276 }
277
278 #[test]
279
280 fn test_number_five() {
281 assert_eq!(
282 check_bracket(
283 &"123+387-321*(322-2)/313+1000-23*23-(3211)/3+3000-1*423+(3*(3*3))-1532/2+4*(231)"
284 .to_string()
285 )
286 .unwrap(),
287 2345
288 );
289 }
290 #[test]
291
292 fn test_power_one() {
293 assert_eq!(check_bracket(&"pow(2,2)".to_string()).unwrap(), 4);
294 }
295
296 #[test]
297
298 fn test_power_two() {
299 assert_eq!(check_bracket(&"pow(9,5)".to_string()).unwrap(), 59049);
300 }
301
302 #[test]
303
304 fn test_sqrt_one() {
305 assert_eq!(check_bracket(&"sqrt(16)".to_string()).unwrap(), 4);
306 }
307
308 #[test]
309
310 fn test_sqrt_two() {
311 assert_eq!(check_bracket(&"sqrt(100)".to_string()).unwrap(), 10);
312 }
313 #[test]
314
315 fn test_sin_one() {
316 assert_eq!(check_bracket(&"sin(0)".to_string()).unwrap(), 0);
317 }
318
319 #[test]
320
321 fn test_sin_two() {
322 assert_eq!(check_bracket(&"sin(90)".to_string()).unwrap(), 1);
323 }
324
325 #[test]
326
327 fn test_cos_one() {
328 assert_eq!(check_bracket(&"cos(0)".to_string()).unwrap(), 1);
329 }
330
331 #[test]
332
333 fn test_cos_two() {
334 assert_eq!(check_bracket(&"cos(90)".to_string()).unwrap(), 0);
335 }
336
337 #[test]
338
339 fn test_fac_one() {
340 assert_eq!(check_bracket(&"(5)!".to_string()).unwrap(), 120);
341 }
342
343 #[test]
344
345 fn test_fac_two() {
346 assert_eq!(check_bracket(&"(2+1)!!".to_string()).unwrap(), 720);
347 }
348
349 #[test]
350
351 fn test_fac_three() {
352 assert_eq!(check_bracket(&"(2+3)!".to_string()).unwrap(), 120);
353 }
354
355 #[test]
356
357 fn test_fac_four() {
358 assert_eq!(check_bracket(&"(3)!!".to_string()).unwrap(), 720);
359 }
360}