mate_rs/lib.rs
1/*!
2This crate provides a library for parsing and calculating arithmetic expressions inputted as &str(string).
3Uses `Lexer` structure to parse string input in to token list, and `Calculator` structure to calculate final result from token list.
4Has also a general wrapper structure that implements `Lexer` and `Calculator` inside of it. And makes it easy to calculate arithmetic
5expression's result directly without dealing with parsing and calculating manually.
6
7# Usage
8
9This crate is on [crates.io](http://crates.io/crates/mate-rs) and can be used by adding mate-rs to your dependencies in your project's `Cargo.toml`.
10```toml
11[dependencies]
12mate-rs = "0.1.4"
13```
14
15# Example: with `Mate`
16
17`Mate` is general wrapper structure for `Lexer` and `Calculator`.
18has only one method that used to `calculate` result via string(&str) input.
19
20```rust
21use mate_rs::mate::Mate;
22
23let result = Mate::calculate("6 * 7");
24match result {
25 Ok(v) => assert_eq!(v, 42.0),
26 Err(_) => {
27 // Do something ...
28 }
29};
30```
31
32# Example: with `Lexer` and `Calculator`
33
34`Lexer` is the main structure that parses string-input to token-list.
35`Calculator` is the structure that used to calculate final result via `Lexer`'s result.
36
37```rust
38use mate_rs::{calculator::Calculator, lexer::Lexer};
39
40// Generated tokens gonna be something like:
41// |
42// | Token(
43// | type: SUBEXP,
44// | tokens: [
45// | Token(
46// | type: SUBEXP,
47// | tokens: [
48// | Token(type: NUMBER, literal: "2")
49// | Token(type: PLUS, literal: "+")
50// | Token(type: NUMBER, literal: "5")
51// | ],
52// | ),
53// | Token(type: PRODUCT, literal: "*"),
54// | Token(
55// | type: SUBEXP,
56// | tokens: [
57// | Token(type: NUMBER, literal: "5")
58// | Token(type: MINUS, literal: "-")
59// | Token(type: NUMBER, literal: "9")
60// | Token(type: PLUS, literal: "+")
61// | Token(
62// | type: SUBEXP,
63// | tokens: [
64// | Token(type: NUMBER, literal: "8")
65// | Token(type: PLUS, literal: "-")
66// | Token(type: NUMBER, literal: "5")
67// | ],
68// | ),
69// | ],
70// | ),
71// | ],
72// | ),
73// | Token(type: PLUS, literal: "+")
74// | Token(type: NUMBER, literal: "35")
75// |
76let input = "[ (2 + 5) * (5 - 9 + (8 - 5)) ] + 35";
77let tokens = Lexer::lex(input.clone()).unwrap(); // should handle error case also
78
79// Result will be calculated from tokens, by X/O/Y algorithm.
80//
81// ╭────────╮ ╭───────────╮ ╭────────╮
82// │ NUMBER │ │ OPERATION │ │ NUMBER │
83// ╰────────╯ ╰───────────╯ ╰────────╯
84// ╰───╮ │ ╭───╯
85// ▼ ▼ ▼
86// X [+, -, *, /] Y
87//
88let result = Calculator::calculate(tokens, input.clone());
89
90match result {
91 Ok(v) => assert_eq!(v, 42.0),
92 Err(_) => {
93 // Do something ...
94 }
95};
96```
97
98> For details refer to [repository](https://github.com/theiskaa/mate).
99*/
100
101pub mod calculator;
102pub mod errors;
103pub mod lexer;
104pub mod mate;
105pub mod monitor;
106pub mod token;
107pub mod utils;