mate-rs 0.2.0

A simple and lightweight arithmetic expression interpreter
Documentation
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//
// Copyright 2022-present theiskaa. All rights reserved.
// Use of this source code is governed by MIT license
// that can be found in the LICENSE file.
//

use crate::utils::ChUtils;

// The structure model for high level sub expression implementations.
// That could hold the actual source: tokens, and transformation method.
//
// For example: in case of parentheses and combinable
// operations(*, /, %) method have to be [PAREN].
// Or, in case of absolute values the method have to be [ABS],
// to let calculator know the approach it has to take to
// return final result of tokens.
#[derive(Clone, Debug, PartialEq)]
pub struct Sub {
    pub tokens: Vec<Token>,
    pub method: SubMethod,
}

impl Sub {
    // Generate a new sub structure data.
    pub fn new(tokens: Vec<Token>, method: SubMethod) -> Self {
        Self { tokens, method }
    }

    // Generates a empty representation of token's sub element.
    pub fn empty() -> Self {
        Self {
            tokens: Vec::new(),
            method: SubMethod::PAREN,
        }
    }
}

// The method type of sub expression -> [Sub].
// Used to decide the final calculation method of sub expression tokens.
// For example, in case of [PAREN] the result will be default result of calculated [tokens].
// Or, in case of [ABS] the result always gonna be positive value.
#[derive(Clone, Debug, PartialEq)]
pub enum SubMethod {
    PAREN,
    ABS,
}

#[derive(Clone, Debug, PartialEq)]
pub enum TokenType {
    ILLEGAL,

    // Internal
    NUMBER,

    // Sub related tokens
    SUBEXP,
    POINTER,
    LPAREN,
    RPAREN,
    LABS,
    RABS,

    // Operations
    PLUS,
    MINUS,
    PRODUCT,
    DIVIDE,
    PERCENTAGE,
    POWER,

    // Math functions
    SQRT,
    SIN,
    COS,
    TAN,
    LOG,
    LN,
    EXP,
    FLOOR,
    CEIL,
    ROUND,
}

// The main structure of input's each parsed character.
#[derive(Clone, Debug, PartialEq)]
pub struct Token {
    pub typ: TokenType,
    pub literal: String,
    pub sub: Sub,
    // the index range of concrete token.
    // [-1] represents the unknown index.
    // left side is the starting point and right side is ending point.
    pub index: (i32, i32),
}

impl TokenType {
    // A function to get valid sub-method from token type.
    //
    // - [TokenType::ABS] is [SubMethod::ABS].
    // - [TokenType::LPAREN] & [TokenType::RPAREN] is [SubMethod::PAREN].
    pub fn to_submethod(&self) -> SubMethod {
        match self {
            TokenType::LABS => SubMethod::ABS,
            TokenType::RABS => SubMethod::ABS,
            _ => SubMethod::PAREN, // + LPAREN, RPAREN
        }
    }
}

impl Token {
    // Define a new Token value by providing all fields.
    pub fn new(typ: TokenType, literal: String, sub: Sub, index: (i32, i32)) -> Self {
        Self {
            typ,
            literal,
            sub,
            index,
        }
    }

    // Create a new sub token model with just sub tokens.
    pub fn new_sub(tokens: Vec<Token>, method: SubMethod) -> Self {
        Self {
            typ: TokenType::SUBEXP,
            literal: String::new(),
            sub: Sub { tokens, method },
            index: Token::unknown_index(),
        }
    }

    // Creates a pointer token, that newer will be used
    // at normal token result.
    pub fn new_pointer(i: usize, method: SubMethod) -> Self {
        Self {
            typ: TokenType::POINTER,
            literal: format!("{i}"),
            sub: Sub::new(Vec::new(), method),
            index: Token::unknown_index(),
        }
    }

    // Create a new token model from a literal.
    // The type is decided automatically by checking it.
    pub fn from(mut literal: String, index: (i32, i32)) -> Self {
        let typ = if literal.is_number() {
            TokenType::NUMBER
        } else {
            match literal.trim().to_lowercase().as_str() {
                "+" => TokenType::PLUS,
                "-" => TokenType::MINUS,
                "*" | "•" => TokenType::PRODUCT,
                "/" | ":" => TokenType::DIVIDE,
                "(" => TokenType::LPAREN,
                ")" => TokenType::RPAREN,
                "%" => TokenType::PERCENTAGE,
                "^" => TokenType::POWER,
                "[" => TokenType::LABS,
                "]" => TokenType::RABS,
                "sqrt" => TokenType::SQRT,
                "sin" => TokenType::SIN,
                "cos" => TokenType::COS,
                "tan" => TokenType::TAN,
                "log" => TokenType::LOG,
                "ln" => TokenType::LN,
                "exp" => TokenType::EXP,
                "floor" => TokenType::FLOOR,
                "ceil" => TokenType::CEIL,
                "round" => TokenType::ROUND,
                _ => TokenType::ILLEGAL,
            }
        };

        // Clear the white-spaces from literal.
        literal.retain(|c| !c.is_whitespace());

        Self {
            typ,
            literal,
            sub: Sub::empty(),
            index,
        }
    }

    // Creates an empty Token model.
    pub fn empty() -> Self {
        Self {
            typ: TokenType::ILLEGAL,
            literal: String::new(),
            sub: Sub::empty(),
            index: (0, 0),
        }
    }

    // A function to get valid sub-method from token.
    //
    // - If [self.typ] is [ABS] is [SubMethod::ABS].
    // - If [self.typ] is [LPAREN] or [RPAREN] is [SubMethod::PAREN].
    pub fn to_submethod(&self) -> SubMethod {
        match &self.typ {
            TokenType::LABS => SubMethod::ABS,
            TokenType::RABS => SubMethod::ABS,
            _ => SubMethod::PAREN, // + LPAREN, RPAREN
        }
    }

    // Returns the default unknown index representation.
    pub fn unknown_index() -> (i32, i32) {
        (-1, -1)
    }

    // Takes the pointer's index as [usize].
    // If current token is not an pointer token, returned option will be [None].
    pub fn take_pointer_index(&self) -> Option<usize> {
        if self.typ != TokenType::POINTER {
            return None;
        }

        self.literal.as_str().parse::<usize>().ok()
    }

    pub fn is_illegal(&self) -> bool {
        matches!(self.typ, TokenType::ILLEGAL)
    }

    pub fn is_lparen(&self) -> bool {
        matches!(self.typ, TokenType::LPAREN)
    }

    pub fn is_rparen(&self) -> bool {
        matches!(self.typ, TokenType::RPAREN)
    }

    pub fn is_pointer(&self) -> bool {
        matches!(self.typ, TokenType::POINTER)
    }

    pub fn is_sub_exp(&self) -> bool {
        matches!(self.typ, TokenType::SUBEXP)
    }

    pub fn is_power(&self) -> bool {
        matches!(self.typ, TokenType::POWER)
    }

    pub fn is_labs(&self) -> bool {
        matches!(self.typ, TokenType::LABS)
    }

    pub fn is_rabs(&self) -> bool {
        matches!(self.typ, TokenType::RABS)
    }

    pub fn is_function(&self) -> bool {
        matches!(
            self.typ,
            TokenType::SQRT
                | TokenType::SIN
                | TokenType::COS
                | TokenType::TAN
                | TokenType::LOG
                | TokenType::LN
                | TokenType::EXP
                | TokenType::FLOOR
                | TokenType::CEIL
                | TokenType::ROUND
        )
    }

    // Checks the "parentheses" family tokens' matching to each other.
    // So, if pointed(self) token is left-parentheses
    // given token(t) should be right-parentheses, if not returns false.
    pub fn matchto(&self, t: &Token) -> bool {
        let m = match self.typ {
            TokenType::LPAREN => TokenType::RPAREN,
            TokenType::LABS => TokenType::RABS,
            _ => TokenType::ILLEGAL,
        };

        m == t.typ
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn new_sub_struct() {
        let test_data: Vec<Sub> = vec![
            Sub {
                tokens: Vec::new(),
                method: SubMethod::PAREN,
            },
            Sub {
                tokens: Vec::new(),
                method: SubMethod::ABS,
            },
        ];

        for sub in test_data {
            let res = Sub::new(sub.clone().tokens, sub.clone().method);
            assert_eq!(res, sub)
        }
    }

    #[test]
    fn empty() {
        let test_data: Vec<Sub> = vec![Sub {
            tokens: Vec::new(),
            method: SubMethod::PAREN,
        }];

        for sub in test_data {
            let res = Sub::empty();
            assert_eq!(res, sub)
        }
    }

    #[test]
    fn to_submethod() {
        assert_eq!(TokenType::LABS.to_submethod(), SubMethod::ABS);
        assert_eq!(TokenType::RABS.to_submethod(), SubMethod::ABS);
        assert_eq!(TokenType::LPAREN.to_submethod(), SubMethod::PAREN);
        assert_eq!(TokenType::RPAREN.to_submethod(), SubMethod::PAREN);
    }

    #[test]
    fn new() {
        let test_data: Vec<Token> = vec![
            Token {
                typ: TokenType::PLUS,
                literal: String::from("+"),
                sub: Sub::empty(),
                index: (0, 0),
            },
            Token {
                typ: TokenType::MINUS,
                literal: String::from("-"),
                sub: Sub::empty(),
                index: (1, 1),
            },
            Token {
                typ: TokenType::DIVIDE,
                literal: String::from("/"),
                sub: Sub::empty(),
                index: (2, 2),
            },
            Token {
                typ: TokenType::SUBEXP,
                literal: String::from(""),
                sub: Sub::new(
                    Vec::from([
                        Token::from(String::from("2"), (0, 0)),
                        Token::from(String::from("+"), (1, 1)),
                        Token::from(String::from("5"), (2, 2)),
                    ]),
                    SubMethod::PAREN,
                ),
                index: (0, 2),
            },
        ];

        for t in test_data {
            let res = Token::new(
                t.clone().typ,
                t.clone().literal,
                t.clone().sub,
                t.clone().index,
            );

            assert_eq!(res.typ, t.clone().typ);
            assert_eq!(res.literal, t.clone().literal);
            assert_eq!(res.sub, t.clone().sub);
            assert_eq!(res.index, t.clone().index);
        }
    }

    #[test]
    fn new_sub() {
        let test_data: HashMap<Vec<String>, Token> = HashMap::from([
            (
                vec![String::from("4"), String::from("+"), String::from("2")],
                Token {
                    typ: TokenType::SUBEXP,
                    literal: String::new(),
                    sub: Sub::new(
                        Vec::from([
                            Token::from(String::from("4"), (0, 0)),
                            Token::from(String::from("+"), (0, 0)),
                            Token::from(String::from("2"), (0, 0)),
                        ]),
                        SubMethod::PAREN,
                    ),
                    index: Token::unknown_index(),
                },
            ),
            (
                vec![String::from("2"), String::from("+"), String::from("+")],
                Token {
                    typ: TokenType::SUBEXP,
                    literal: String::new(),
                    sub: Sub::new(
                        Vec::from([
                            Token::from(String::from("2"), (0, 0)),
                            Token::from(String::from("+"), (0, 0)),
                            Token::from(String::from("+"), (0, 0)),
                        ]),
                        SubMethod::PAREN,
                    ),
                    index: Token::unknown_index(),
                },
            ),
        ]);

        for (t, expected) in test_data {
            let tokens = t.into_iter().map(|tt| Token::from(tt, (0, 0))).collect();
            let res = Token::new_sub(tokens, SubMethod::PAREN);

            assert_eq!(res.typ, expected.clone().typ);
            assert_eq!(res.literal, expected.clone().literal);
            assert_eq!(res.sub, expected.clone().sub);
            assert_eq!(res.index, expected.clone().index);
        }
    }

    #[test]
    fn new_pointer() {
        let test_data: HashMap<usize, Token> = HashMap::from([
            (
                0,
                Token::new(
                    TokenType::POINTER,
                    String::from("0"),
                    Sub::new(Vec::new(), SubMethod::PAREN),
                    (-1, -1),
                ),
            ),
            (
                99,
                Token::new(
                    TokenType::POINTER,
                    String::from("99"),
                    Sub::new(Vec::new(), SubMethod::ABS),
                    (-1, -1),
                ),
            ),
        ]);

        for (i, expected) in test_data {
            let token: Token = Token::new_pointer(i, expected.clone().sub.method);
            assert_eq!(token, expected);
        }
    }

    #[test]
    fn from() {
        let test_data: HashMap<(String, (i32, i32)), Token> = HashMap::from([
            (
                (String::from("42"), (0, 1)),
                Token::new(TokenType::NUMBER, String::from("42"), Sub::empty(), (0, 1)),
            ),
            (
                (String::from("}"), (0, 0)),
                Token::new(TokenType::ILLEGAL, String::from("}"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("+"), (0, 0)),
                Token::new(TokenType::PLUS, String::from("+"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("-"), (0, 0)),
                Token::new(TokenType::MINUS, String::from("-"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("*"), (0, 0)),
                Token::new(TokenType::PRODUCT, String::from("*"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("•"), (0, 0)),
                Token::new(TokenType::PRODUCT, String::from("•"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("/"), (0, 0)),
                Token::new(TokenType::DIVIDE, String::from("/"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from(":"), (0, 0)),
                Token::new(TokenType::DIVIDE, String::from(":"), Sub::empty(), (0, 0)),
            ),
            (
                (String::from("%"), (0, 0)),
                Token::new(
                    TokenType::PERCENTAGE,
                    String::from("%"),
                    Sub::empty(),
                    (0, 0),
                ),
            ),
        ]);

        for (v, expected) in test_data {
            let res = Token::from(v.0, v.1);
            assert_eq!(res, expected);
        }
    }

    #[test]
    fn unknown_index() {
        assert_eq!(Token::unknown_index(), (-1, -1));
    }

    #[test]
    fn take_pointer_index() {
        let test_data: HashMap<Option<usize>, Token> = HashMap::from([
            (None, Token::from(String::from("25"), (0, 1))),
            (None, Token::from(String::from("-"), (0, 0))),
            (Some(0), Token::new_pointer(0, SubMethod::PAREN)),
            (Some(9), Token::new_pointer(9, SubMethod::PAREN)),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.take_pointer_index());
        }
    }

    #[test]
    fn is_illegal() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (true, Token::from(String::from("}"), (0, 0))),
            (true, Token::from(String::from("|"), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_illegal());
        }
    }

    #[test]
    fn is_lparen() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from(")"), (0, 0))),
            (true, Token::from(String::from("("), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_lparen());
        }
    }

    #[test]
    fn is_rparen() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("("), (0, 0))),
            (true, Token::from(String::from(")"), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_rparen());
        }
    }

    #[test]
    fn is_pointer() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("("), (0, 0))),
            (true, Token::new_pointer(0, SubMethod::PAREN)),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_pointer());
        }
    }

    #[test]
    fn is_sub_exp() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("("), (0, 0))),
            (true, Token::new_sub(vec![], SubMethod::PAREN)),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_sub_exp());
        }
    }

    #[test]
    fn is_power() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("("), (0, 0))),
            (true, Token::from(String::from("^"), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_power());
        }
    }

    #[test]
    fn is_labs() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("]"), (0, 0))),
            (true, Token::from(String::from("["), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_labs());
        }
    }

    #[test]
    fn is_rabs() {
        let test_data: HashMap<bool, Token> = HashMap::from([
            (false, Token::from(String::from("-25"), (0, 1))),
            (false, Token::from(String::from("-"), (0, 0))),
            (false, Token::from(String::from("["), (0, 0))),
            (true, Token::from(String::from("]"), (0, 0))),
        ]);

        for (expected, token) in test_data {
            assert_eq!(expected, token.is_rabs());
        }
    }

    #[test]
    fn matchto() {
        let test_data: HashMap<bool, (Token, Token)> = HashMap::from([
            (
                true,
                (
                    Token::from(String::from("("), (0, 0)),
                    Token::from(String::from(")"), (0, 0)),
                ),
            ),
            (
                true,
                (
                    Token::from(String::from("["), (0, 0)),
                    Token::from(String::from("]"), (0, 0)),
                ),
            ),
            (
                false,
                (
                    Token::from(String::from("0"), (0, 0)),
                    Token::from(String::from("1"), (0, 0)),
                ),
            ),
        ]);

        for (expected, tokens) in test_data {
            assert_eq!(expected, tokens.0.matchto(&tokens.1));
        }
    }
}