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
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use better_term::{Color, Style};
use crate::input_reader::InputReader;
use crate::interpret::{interpret, interpret_with_definitions};

pub(crate) mod lex;
pub(crate) mod input_reader;
pub(crate) mod postfix;
pub(crate) mod interpret;
pub(crate) mod operator;

/// rounds a f64 to a specific decimal place
/// # Arguments
/// * value - the value to round
/// * places - the number of decimal places to round to
/// # Returns the rounded value
///
/// # Example
/// ```
/// use calc_lib::round;
///
/// assert_eq!(round(1.2345, 2), 1.23);
/// ```
pub fn round(value: f64, place: usize) -> f64 {
    let round_by = 10.0f64.powi(place as i32) as f64;
    (value * round_by).round() / round_by
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct InputPos {
    line: usize,
    ch: usize,
}

impl InputPos {
    pub(crate) fn new(line: usize, ch: usize) -> Self {
        Self {
            line, ch
        }
    }

    pub(crate) fn next(&mut self) {
        self.ch += 1
    }

    pub(crate) fn newline(&mut self) {
        self.line += 1;
        self.ch = 0;
    }
}

impl Default for InputPos {
    fn default() -> Self {
        Self::new(1, 1)
    }
}

impl Display for InputPos {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "{}:{}", self.line, self.ch)
    }
}

/// Stores errors from the parser if any occur.
/// error: The message of the error. Accessed with `.get_error()`
/// pos: The position of the error. Accessed with `.get_pos()`
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Error {
    error: String,
    pos: Option<InputPos>,
}

impl Error {
    pub(crate) fn new<S: Into<String>>(msg: S, pos: InputPos) -> Self {
        Self {
            error: msg.into(),
            pos: Some(pos),
        }
    }

    pub(crate) fn new_gen<S: Into<String>>(msg: S) -> Self {
        Self {
            error: msg.into(),
            pos: None,
        }
    }

    pub fn create<S: Into<String>>(msg: S) -> Self {
        Self::new_gen(msg.into())
    }

    /// Returns the error message.
    pub fn get_error(&self) -> &str {
        &self.error
    }

    /// returns the location of the error as (line, character)
    /// this struct uses a private `InputPos` struct to store the position,
    /// but that is not exposed to the user.
    pub fn get_loc(&self) -> (usize, usize) {
        (self.pos.as_ref().unwrap().line, self.pos.as_ref().unwrap().ch)
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let strong_red = Style::default().fg(Color::Red).bold();
        let strong_white = Style::default().fg(Color::BrightWhite).bold();
        let reset = Style::reset();
        if self.pos.is_some() {
            write!(f, "{}error: {}{}{}\n  {}-> {}{}",
                   strong_red, strong_white, self.error, reset,
                   Color::BrightBlue, Color::BrightBlack, self.pos.as_ref().unwrap()
            )
        } else {
            write!(f, "{}error: {}{}{}",
                   strong_red, strong_white, self.error, reset)
        }
    }
}

#[derive(Debug, Clone)]
pub struct Number {
    value: f64,
}

impl Number {
    pub fn new<N: Into<f64>>(n: N) -> Self {
        Self {
            value: n.into(),
        }
    }

    pub fn negate(&mut self) {
        self.value = -self.value;
    }

    pub fn as_f64(&self) -> f64 {
        self.value
    }

    pub fn as_i128(&self) -> i128 {
        self.value.round() as i128
    }
}

impl Display for Number {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", if self.value.fract() == 0.0 {
            self.as_i128().to_string()
        } else {
            self.value.to_string()
        })
    }
}

/// A list of definitions to pass into the crate to be used in the interpreter.
pub type Definitions = HashMap<String, Number>;

/// A list of definitions of functions to pass into the interpreter to solve for the variables.
pub struct Functions<'a> {
    pub(crate) functions: HashMap<String, Box<dyn Fn(Vec<Number>) -> Result<Number, Error> + 'a>>,
}

impl<'a> Functions<'a> {
    pub fn new() -> Self {
        Self {
            functions: HashMap::new(),
        }
    }

    pub fn register<S: Into<String>, F: Fn(Vec<Number>) -> Result<Number, Error> + 'a + Copy>(&mut self, name: S, f: F) {
        self.functions.insert(name.into(), Box::new(f));
    }

    pub fn get<S: Into<String>>(&self, ident: S) -> Option<&Box<dyn Fn(Vec<Number>) -> Result<Number, Error> + 'a>> {
        let ident = ident.into();
        if !self.functions.contains_key(&ident) {
            return None;
        }
        self.functions.get(&ident)
    }
}

impl Default for Functions<'_> {
    fn default() -> Self {
        let mut funcs = Functions::new();
        funcs.register("log", |args| {
            if args.len() != 2 {
                return Err(Error::create(format!("log takes exactly 2 arguments, {} given", args.len())));
            }
            Ok(Number::new(args[1].as_f64().log(args[0].as_f64())))
        });

        funcs.register("sqrt", |args| {
            if args.len() != 1 {
                return Err(Error::create(format!("sqrt takes exactly 1 argument, {} given", args.len())));
            }
            Ok(Number::new(args[0].as_f64().sqrt()))
        });

        funcs
    }
}

/// Solves an equation in infix notation using the shunting yard algorithm.
/// this function will not accept decimals numbers, only integers.
/// # Usage Example:
/// ```
/// use calc_lib::solve;
///
/// let x = solve("(1 + 2) * 3");
/// if x.is_err() {
///     panic!("{}", x.unwrap_err());
/// }
/// assert_eq!(x.unwrap().as_i128(), 9);
/// ```
///
pub fn solve<S: Into<String>>(input: S) -> Result<Number, Error> {
    let mut input = InputReader::new(input.into());
    let mut tokens = lex::lex(&mut input, false)?;
    let mut shunted = postfix::shunting_yard(&mut tokens)?;
    interpret(&mut shunted)
}

/// Solves an equation in infix notation using the shunting yard algorithm.
/// This will not accept decimal numbers, only integers.
/// this function takes a HashMap of definitions (type Definitions<i128>)
/// and will replace identifiers found in the equation with their respective values.
///
/// # Usage Example:
/// ```
/// use calc_lib::{Definitions, Number, solve_defs};
///
/// let mut defs = Definitions::new();
/// defs.insert("x".to_string(), Number::new(3));
///
/// let solved = solve_defs("(x + 3) / 3", Some(&defs), None);
/// assert_eq!(solved.unwrap().as_i128(), 2);
/// ```
///
/// # Usage with functions:
/// ```
/// use calc_lib::{Definitions, Functions, Number, Error, solve_defs};
///
/// let mut defs = Definitions::new();
/// defs.insert("x".to_string(), Number::new(3));
///
/// let mut funcs = Functions::new();
/// funcs.register("log", |args| {
///     if args.len() != 2 {
///         return Err(Error::create(format!("log takes exactly 2 arguments, {} given", args.len())));
///     }
///     Ok(Number::new(args[1].as_f64().log(args[0].as_f64())))
///  });
///
/// let solved = solve_defs("log(2, 16)", Some(&defs), Some(&funcs));
/// assert_eq!(solved.unwrap().as_i128(), 4);
/// ```
///
pub fn solve_defs<S: Into<String>>(input: S, definitions: Option<&Definitions>, functions: Option<&Functions>) -> Result<Number, Error> {
    let mut input = InputReader::new(input.into());
    let mut tokens = lex::lex(&mut input, true)?;
    let mut shunted = postfix::shunting_yard(&mut tokens)?;
    interpret_with_definitions(&mut shunted, definitions, functions)
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_shunt() {
        let solved = solve("1 + 2 * 3");
        if solved.is_err() {
            panic!("{}", solved.err().unwrap());
        }
        assert_eq!(solved.unwrap().as_i128(), 7);
        let x = solve("1.3 + 2.5 * 3.1");
        if x.is_err() {
            panic!("{}", x.unwrap_err());
        }
        assert_eq!(x.unwrap().as_f64(), 9.05);

        let mut defs = Definitions::new();
        defs.insert("x".to_string(), Number::new(16));


        let solved3 = solve_defs("(x + 4) / 5.0", Some(&defs), None);
        assert_eq!(solved3.unwrap().as_f64(), 4.0);

        let funcs = Functions::default();
        let solved4 = solve_defs("log(2, x)", Some(&defs), Some(&funcs));
        if solved4.is_err() {
            panic!("{}", solved4.unwrap_err());
        }
        assert_eq!(solved4.unwrap().as_f64(), 4.0);
    }
}