Skip to main content

Parser_calculator/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub mod error;
4use std::char;
5
6use error::{CalcError, Res};
7#[derive(pest_derive::Parser)]
8#[grammar = "grammar.pest"]
9pub struct ParserCalculator;
10
11/// Це парсер математичних виразів який бере наш вираз(input) та парсить його на
12/// основні складові: числа, знаки, дужки.
13/// Вираз складається з:
14/// - Числа
15/// - Нуль або більше операторів та чисел
16/// - Нуль або більше дужок з виразами всередині
17///
18/// Порядок обчислення стандартний:
19/// 1. Дужки
20/// 2. Множення і ділення
21/// 3. Додавання і віднімання
22
23pub fn pars(input: &str) -> Res<i32> {
24    if input.trim().is_empty() {
25        return Err(CalcError::EmptyExp);
26    }
27    let input = input.trim();
28    check_bracket(&input.to_string())
29}
30/// Функція що видаляє коментарі та зайві пробіли
31pub fn remove_spaces(input: &String) -> String {
32    let mut res = String::new();
33    let mut chars = input.chars().peekable();
34    while let Some(&c) = chars.peek() {
35        match c {
36            ' ' | '\t' | '\n' => {
37                chars.next();
38            }
39            '#' => {
40                while let Some(&c) = chars.peek() {
41                    chars.next();
42                    if c == '\n' {
43                        break;
44                    }
45                }
46            }
47            _ => {
48                res.push(c);
49                chars.next();
50            }
51        }
52    }
53    res
54}
55/// Функція шукає дужки у нашому виразі, якщо знаходить то
56/// обчислюємо значення в дужках та замінюємо цей вираз з дужками на саме значення.
57pub fn check_bracket(input: &String) -> Res<i32> {
58    let input = remove_spaces(input);
59    if input.contains("pow") {
60        return to_power(&input);
61    }
62    if input.contains("sqrt") {
63        return to_sqrt(&input);
64    }
65    if input.contains("sin") {
66        return sin_func(&input);
67    }
68    if input.contains("cos") {
69        return cos_func(&input);
70    }
71    if input.contains("!") && input.contains('(') && input.contains(')') {
72        return fac_func(&input);
73    }
74    if input.starts_with("-") {
75        return unary_func(&input);
76    }
77    if input.starts_with("|") && input.ends_with("|") {
78        return abs_func(&input);
79    }
80    let mut new_input = input.clone();
81    while new_input.contains('(') && new_input.contains(')') {
82        let input_chars: Vec<char> = new_input.chars().collect();
83        let mut open_bracket: Option<usize> = None;
84        let mut close_bracket: Option<usize> = None;
85
86        for (a, &c) in input_chars.iter().enumerate() {
87            if c == '(' {
88                open_bracket = Some(a);
89            } else if c == ')' && open_bracket.is_some() {
90                close_bracket = Some(a);
91                break;
92            }
93        }
94        if open_bracket.is_none() || close_bracket.is_none() {
95            return Err(CalcError::NoBracket);
96        }
97
98        let index_start = open_bracket.unwrap();
99        let index_end = close_bracket.unwrap();
100        let in_bracket = input_chars[index_start + 1..index_end].iter().collect();
101
102        let num_in_bracket = parse_number(&in_bracket);
103        let sign_in_bracket = parse_sign(&in_bracket);
104        let value_bracket = calc(num_in_bracket, sign_in_bracket)?;
105
106        new_input.replace_range(index_start..=index_end, &value_bracket.to_string());
107    }
108    let number_input: Vec<i32> = parse_number(&new_input);
109    let sign_input: Vec<char> = parse_sign(&new_input);
110
111    calc(number_input, sign_input)
112}
113
114/// Парсимо input на числа.
115/// Для цього ми замінюємо всі знаки на пробіли і потім
116/// парсимо по пробілам наші числв.
117/// Число - це одна або більше цифр(0-9).
118pub fn parse_number(input: &String) -> Vec<i32> {
119    let number: Vec<i32> = input
120        .replace("+", " ")
121        .replace("-", " ")
122        .replace("*", " ")
123        .replace("/", " ")
124        .split_whitespace()
125        .filter_map(|n| n.parse::<i32>().ok())
126        .collect();
127    println!("{:?}", number);
128    number
129}
130
131/// Парсимо input на знаки.
132/// Для цього ми просто використовуємо метод filtre щоб відфільтрувати
133/// всі знаки від інших символів та чисел.
134/// Підтримуються знаки: +, -. *, /
135
136pub fn parse_sign(input: &String) -> Vec<char> {
137    let ch: Vec<char> = input
138        .chars()
139        .filter(|c| *c == '+' || *c == '-' || *c == '*' || *c == '/')
140        .collect();
141
142    println!("{:?}", ch);
143    ch
144}
145
146/// Функція яка обчислює значення виразу приймаючи як аргумент ветор
147/// з числами та знаками. Спочатку ми шукаємо "*" та "/" щоб виконати ці дії,
148/// обчислюємо число яке стоїть на місці(a) індекса знака "*" або "/" з a+1
149/// та отримуємо значення. Потім додавання та віднімання.
150
151pub fn calc(mut number: Vec<i32>, mut ch: Vec<char>) -> Res<i32> {
152    if number.is_empty() {
153        return Err(CalcError::EmptyExp);
154    }
155    let mut b = 0;
156    while b < ch.len() {
157        if b + 1 >= number.len() {
158            break;
159        }
160        if ch[b] == '*' {
161            number[b] *= number[b + 1];
162            number.remove(b + 1);
163            ch.remove(b);
164        } else if ch[b] == '/' {
165            if number[b + 1] == 0 {
166                return Err(CalcError::DivByZero);
167            }
168            number[b] /= number[b + 1];
169            number.remove(b + 1);
170            ch.remove(b);
171        } else {
172            b += 1;
173        }
174    }
175
176    let mut res = number[0];
177    for a in 0..ch.len() {
178        if a + 1 >= number.len() {
179            break;
180        }
181        if ch[a] == '+' {
182            res += number[a + 1];
183        } else if ch[a] == '-' {
184            res -= number[a + 1];
185        }
186    }
187
188    Ok(res)
189}
190
191pub fn to_power(input: &String) -> Res<i32> {
192    let mut res: i32 = 1;
193    let replace_input: String = input.replace("pow(", "").replace(")", "");
194    if replace_input.is_empty() {
195        return Err(CalcError::EmptyExp);
196    }
197    let numbers: Vec<i32> = replace_input
198        .replace(",", " ")
199        .split(" ")
200        .map(|s| s.parse().unwrap())
201        .collect();
202    let number = numbers[0];
203    let power = numbers[1];
204    for _ in 0..power as usize {
205        res *= number;
206    }
207    Ok(res)
208}
209
210pub fn to_sqrt(input: &String) -> Res<i32> {
211    let replcae_input: String = input.replace("sqrt(", "").replace(")", "");
212
213    if replcae_input.is_empty() {
214        return Err(CalcError::EmptyExp);
215    }
216    let number = replcae_input.parse().unwrap();
217    let mut res: i32 = 0;
218    for i in 1..number {
219        if i * i == number {
220            res = i;
221            break;
222        }
223    }
224    Ok(res)
225}
226
227pub fn sin_func(input: &String) -> Res<i32> {
228    let num = input.replace("sin(", "").replace(")", "");
229    let num: f64 = num.parse().unwrap();
230    Ok(num.to_radians().sin().round() as i32)
231}
232
233pub fn cos_func(input: &String) -> Res<i32> {
234    let num = input.replace("cos(", "").replace(")", "");
235    let num: f64 = num.parse().unwrap();
236    Ok(num.to_radians().cos().round() as i32)
237}
238
239pub fn fac_func(input: &String) -> Res<i32> {
240    if input.is_empty() {
241        return Err(CalcError::EmptyExp);
242    }
243    let mut res = 1;
244    let mut count = 0;
245    for i in input.chars() {
246        if i == '!' {
247            count += 1;
248        }
249    }
250    if count == 1 {
251        let num = input.replace("!", "");
252        let num: i32 = if num.contains('(') || num.contains('+') || num.contains('-') {
253            check_bracket(&num)?
254        } else {
255            num.parse().map_err(|_| CalcError::InvalidInput)?
256        };
257        for i in 1..=num {
258            res *= i;
259        }
260    } else if count == 2 {
261        let num = input.replace("(", "").replace("!", "").replace(")", "");
262        let num: i32 = if num.contains('(') || num.contains('+') || num.contains('-') {
263            check_bracket(&num)?
264        } else {
265            num.parse().map_err(|_| CalcError::InvalidInput)?
266        };
267
268        for i in 1..=num {
269            res *= i;
270        }
271        let temp = res;
272        res = 1;
273        for i in 1..=temp {
274            res *= i;
275        }
276    } else {
277        return Err(CalcError::InvalidInput);
278    }
279
280    Ok(res)
281}
282
283pub fn unary_func(input: &String) -> Res<i32> {
284    let num = input.trim_matches('-').to_string();
285    let num: i32 = if num.contains('(')
286        || num.contains('+')
287        || num.contains('-')
288        || num.contains('*')
289        || num.contains('/')
290    {
291        check_bracket(&num)?
292    } else {
293        num.parse().map_err(|_| CalcError::InvalidInput)?
294    };
295    Ok(-num)
296}
297
298pub fn abs_func(input: &String) -> Res<i32> {
299    let num = input.trim_matches('|').to_string();
300    let num: i32 = if num.contains('(')
301        || num.contains('+')
302        || num.contains('-')
303        || num.contains('*')
304        || num.contains('/')
305    {
306        check_bracket(&num)?
307    } else {
308        num.parse().map_err(|_| CalcError::InvalidInput)?
309    };
310    Ok(num.abs())
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    #[test]
317    fn test_number_one() {
318        assert_eq!(check_bracket(&"12+(3*1)*2".to_string()).unwrap(), 18);
319    }
320
321    #[test]
322    fn test_number_two() {
323        assert_eq!(check_bracket(&"(2+3)*5-25".to_string()).unwrap(), 0);
324    }
325
326    #[test]
327
328    fn test_number_three() {
329        assert_eq!(check_bracket(&"2*(2*(2*2))".to_string()).unwrap(), 16);
330    }
331
332    #[test]
333
334    fn test_number_four() {
335        assert_eq!(
336            check_bracket(&"200+200+100*(100+100)-(100-90)".to_string()).unwrap(),
337            20390
338        );
339    }
340
341    #[test]
342
343    fn test_number_five() {
344        assert_eq!(
345            check_bracket(
346                &"123+387-321*(322-2)/313+1000-23*23-(3211)/3+3000-1*423+(3*(3*3))-1532/2+4*(231)"
347                    .to_string()
348            )
349            .unwrap(),
350            2345
351        );
352    }
353    #[test]
354
355    fn test_power_one() {
356        assert_eq!(check_bracket(&"pow(2,2)".to_string()).unwrap(), 4);
357    }
358
359    #[test]
360
361    fn test_power_two() {
362        assert_eq!(check_bracket(&"pow(9,5)".to_string()).unwrap(), 59049);
363    }
364
365    #[test]
366
367    fn test_sqrt_one() {
368        assert_eq!(check_bracket(&"sqrt(16)".to_string()).unwrap(), 4);
369    }
370
371    #[test]
372
373    fn test_sqrt_two() {
374        assert_eq!(check_bracket(&"sqrt(100)".to_string()).unwrap(), 10);
375    }
376    #[test]
377
378    fn test_sin_one() {
379        assert_eq!(check_bracket(&"sin(0)".to_string()).unwrap(), 0);
380    }
381
382    #[test]
383
384    fn test_sin_two() {
385        assert_eq!(check_bracket(&"sin(90)".to_string()).unwrap(), 1);
386    }
387
388    #[test]
389
390    fn test_cos_one() {
391        assert_eq!(check_bracket(&"cos(0)".to_string()).unwrap(), 1);
392    }
393
394    #[test]
395
396    fn test_cos_two() {
397        assert_eq!(check_bracket(&"cos(90)".to_string()).unwrap(), 0);
398    }
399
400    #[test]
401
402    fn test_fac_one() {
403        assert_eq!(check_bracket(&"(5)!".to_string()).unwrap(), 120);
404    }
405
406    #[test]
407
408    fn test_fac_two() {
409        assert_eq!(check_bracket(&"(2+1)!!".to_string()).unwrap(), 720);
410    }
411
412    #[test]
413
414    fn test_fac_three() {
415        assert_eq!(check_bracket(&"(2+3)!".to_string()).unwrap(), 120);
416    }
417
418    #[test]
419
420    fn test_fac_four() {
421        assert_eq!(check_bracket(&"(3)!!".to_string()).unwrap(), 720);
422    }
423    #[test]
424
425    fn test_unary_one() {
426        assert_eq!(check_bracket(&"-5".to_string()).unwrap(), -5);
427    }
428
429    #[test]
430
431    fn test_unary_two() {
432        assert_eq!(check_bracket(&"-(3+2)".to_string()).unwrap(), -5);
433    }
434
435    #[test]
436
437    fn test_unary_three() {
438        assert_eq!(check_bracket(&"-(2*(3+2))".to_string()).unwrap(), -10);
439    }
440
441    #[test]
442
443    fn test_abs_one() {
444        assert_eq!(check_bracket(&"|-5|".to_string()).unwrap(), 5);
445    }
446
447    #[test]
448
449    fn test_abs_two() {
450        assert_eq!(check_bracket(&"|2-5|".to_string()).unwrap(), 3);
451    }
452
453    #[test]
454
455    fn test_remove_spaces_one() {
456        assert_eq!(check_bracket(&"12+3*4 #comment".to_string()).unwrap(), 24);
457    }
458
459    #[test]
460
461    fn test_remove_spaces_two() {
462        assert_eq!(
463            check_bracket(&"12 + 3 * 4 #вираз\n+1".to_string()).unwrap(),
464            25
465        );
466    }
467}