num_parser2/
lib.rs

1//!
2//! # num_parser2: a math interpreter and evaluator
3//! 
4//! [![crate](https://img.shields.io/crates/v/num_parser2)](https://crates.io/crates/num_parser2)
5//! [![license](https://img.shields.io/github/license/0xJWLabs/num_parser2)](https://github.com/0xJWLabs/num_parser2/blob/main/LICENSE)
6//! [![docs](https://img.shields.io/docsrs/num_parser2)](https://docs.rs/num_parser2/1.0.2/num_parser2/)
7//! 
8//! **num_parser2** allows you to easily **parse** strings into math expressions
9//! and **evaluate** them.
10//!
11//! ## Features
12//! * Binary and unary operators
13//! * Supports **multiple value types**:
14//!     * Bool,
15//!     * Int,
16//!     * Float,
17//!     * [Complex](num::complex::Complex64),
18//!     * Vector
19//! * Built-in functions
20//! * Built-in constants
21//! * **User-defined functions**: `f(x,y) = xsin(y)+ysin(x)`
22//! * **User-defined var**: `a = pi/2` or `b = a+2`
23//! * Define you own functions with **macros**.
24//! * Understands **ambiguous syntax**, like: `g(x) = pisinx`
25//! * **Recursion**: `f(x) = branch(x<=2, 1, f(x-1)+f(x-2))`
26//! * Serde support
27//! * No panicking
28//!
29//! Much more will be implemented in future releases!
30//!
31//! ## Use Guide
32//!
33//! Evaluating **simple static expressions**:
34//! ```
35//! use num_parser2::*;
36//!
37//! assert_eq!(eval("2+2").unwrap(), Value::from(4));
38//! assert_eq!(eval("sin(pi)").unwrap(), Value::from(0));
39//! assert_eq!(eval("re(10+3i)").unwrap(), Value::from(10));
40//! ```
41//!
42//! Using **contexts**:
43//!
44//! ```
45//! use num_parser2::*;
46//!
47//! let mut context = Context::default();
48//! // Declaring a function
49//! let res = eval_with_mutable_context(
50//!     "f(x) = branch(x<=2, 1, f(x-1) + f(x-2))",
51//!     &mut context
52//! ).unwrap();
53//!
54//! // Result is None
55//! assert_eq!(res, None);
56//! // Calling the function. We could just use eval_with_static_context at this point
57//! let res = eval_with_mutable_context("f(10)", &mut context).unwrap();
58//!
59//! assert_eq!(res, Some(Value::from(55)));
60//! ```
61//!
62//! ## Values
63//! **Values** are contained inside the [Value enum](Value), which provides useful functions
64//! to access the contained data:
65//!
66//! ```rust
67//! use num_parser2::Value;
68//!
69//! let value = Value::Float(1.0);
70//!
71//! assert_eq!(value.as_bool().unwrap(), true);
72//! assert_eq!(value.as_int().unwrap(), 1);
73//! assert_eq!(value.as_float().unwrap(), 1.0);
74//! assert_eq!(value.as_complex().unwrap(), num::complex::Complex::new(1.0, 0.0));
75//! assert_eq!(value.as_vector(), vec![Value::Float(1.0)]);
76//!
77//! // Assign type implicitly:
78//! let implicit = Value::from(1.0);
79//!
80//! assert_eq!(value, implicit);
81//! ```
82//!
83//! Note that, even thought the initial value was a float, it has been **cast** into ints and bools. This
84//! was possible since the value had no decimal part and it was a one. If these conditions were not
85//! met, the cast would have failed.
86//!
87//! ## Operators
88//! **Binary** operators:
89//!
90//! | Operator | Description | Precedence |
91//! |----------|-------------|------------|
92//! | ^  | Exponentiation                                       | 90 |
93//! | /  | Division                                             | 70 |
94//! | *  | Multiplication                                       | 70 |
95//! | %  | Modulo                                               | 70 |
96//! | +  | Sum                                                  | 60 |
97//! | -  | Subtraction                                          | 60 |
98//! | <  | Less than                                            | 50 |
99//! | >  | Greater than                                         | 50 |
100//! | <= | Less or equal to                                     | 50 |
101//! | >= | Greater or equal to                                  | 50 |
102//! | == | Equal to                                             | 40 |
103//! | != | Not equal to                                         | 40 |
104//! | && | Logical AND                                          | 30 |
105//! | &#124;&#124; | Logical OR                                 | 20 |
106//! | ,  | Aggregation. Creates vectors                         | 10 |
107//! | =  | Assignment. Used for functions and vars declarations | 0  |
108//!
109//! **Unary** operators:
110//!
111//! | Operator | Description | Precedence |
112//! |----------|-------------|------------|
113//! | ! | Logical NOT | 80 |
114//! | - | Negation    | 60 |
115//!
116//! ## Functions
117//!
118//! | Function | Parameters Amount          | Description                                                   |
119//! |----------|----------------------------|---------------------------------------------------------------|
120//! | `min`    | >=1                        | Returns the minimum value.                                    |
121//! | `max`    | >=1                        | Returns the maximum value.                                    |
122//! | `floor`  | 1                          | Returns the greatest lower integer.                           |
123//! | `ceil`   | 1                          | Returns the lowest greater integer.                           |
124//! | `round`  | 1                          | Returns the rounded integer.                                  |
125//! | `ln`     | 1                          | Returns the natural log of the number.                        |
126//! | `log`    | 2 (base, arg)              | Returns the logarithm of the number with the specified base.  |
127//! | `exp`    | 1                          | Returns e^(arg).                                              |
128//! | `abs`    | 1                          | Returns the absolute value of a number.                       |
129//! | `sqrt`   | 1                          | Returns the square root of a number.                          |
130//! | `rand`   | 2 (min, max)               | Returns a random float between the two number specified.      |
131//! | `branch` | 3 (condition, true, false) | Returns the second argument if the condition is true, the third if it is false. |
132//! | `sin`    | 1                          | Returns the sine of the angle.                                |
133//! | `cos`    | 1                          | Returns the cosine of the angle.                              |
134//! | `tan`    | 1                          | Returns the tangent of the angle.                             |
135//! | `asin`   | 1                          | Returns the arcsine of the angle.                             |
136//! | `acos`   | 1                          | Returns the arccosine of the angle.                           |
137//! | `atan`   | 1                          | Returns the arctangent of the angle.                          |
138//! | `sinh`   | 1                          | Returns the hyperbolic sine of the angle.                     |
139//! | `cosh`   | 1                          | Returns the hyperbolic cosine of the angle.                   |
140//! | `tanh`   | 1                          | Returns the hyperbolic tangent of the angle.                  |
141//! | `asinh`  | 1                          | Returns the hyperbolic arcsine of the angle.                  |
142//! | `acosh`  | 1                          | Returns the hyperbolic arccosine of the angle.                |
143//! | `atanh`  | 1                          | Returns the hyperbolic arctangent of the angle.               |
144//! | `re`     | 1                          | Returns the natural part of the number.                       |
145//! | `im`     | 1                          | Returns the imaginary part of the number.                     |
146//! | `polar`  | 1                          | Returns the polar form (r, theta) of the complex number.      |
147//! | `arg`    | 1                          | Returns the principal arg of the number.                      |
148//! | `norm`   | 1                          | Returns the length of the vector (re, im).                    |
149//!
150//! ## Context
151//!
152//! [Contexts](Context) allows you keep track of **user-defined functions** and **variables**, as well
153//! as settings. They can be created as follows:
154//!
155//! ```rust
156//! use num_parser2::*;
157//!
158//! // Generate the default context
159//! let mut default = Context::default();
160//!
161//! // Generate a custom context
162//! let mut custom = Context::new(
163//!     settings::Rounding::NoRounding,
164//!     settings::AngleUnit::Degree,
165//!     settings::DepthLimit::NoLimit
166//! );
167//! ```
168//!
169//! ### Serde
170//!
171//! You can use the optional feature `serde_support` to let all the public structs
172//! derive  [`Serialize`](https://docs.rs/serde/1.0.71/serde/trait.Serializer.html) and
173//! [`Deserialize`](https://docs.rs/serde/1.0.71/serde/trait.Serializer.html).
174//!
175//! ```text
176//! [dependencies]
177//! num = { version = "<version>", features = [ "serde_support" ] }
178//! ```
179//!
180//! ## License and contribution
181//! num_parser2 is licensed under a **MIT License**.
182//!
183//! Feel free to open issues and pull requests for any problems or ideas you come up with.
184//!
185
186#[cfg(feature = "serde_support")]
187extern crate serde;
188
189extern crate num;
190
191pub mod function;
192
193mod api;
194
195mod context;
196mod interpreter;
197mod objects;
198mod operators;
199mod out;
200mod token;
201mod tree;
202mod value;
203
204pub use crate::{
205    api::*,
206    context::{settings, Context},
207    objects::Expression,
208    out::*,
209    value::{valuetype::*, Value},
210};