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
use crate::{definitions::N_UNARYOPS_OF_DEEPEX_ON_STACK, ExError, ExResult};
use num::Float;
use smallvec::{smallvec, SmallVec};
use std::{fmt::Debug, marker::PhantomData};

fn make_op_not_available_error<'a>(repr: &'a str) -> ExError {
    ExError {
        msg: format!("operator {} not available", repr),
    }
}

/// Operators can be custom-defined by the library-user in terms of this struct.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct Operator<'a, T: Copy> {
    /// Representation of the operator in the string to be parsed, e.g., `-` or `sin`.
    repr: &'a str,
    /// Binary operator that contains a priority besides a function pointer.
    bin_op: Option<BinOp<T>>,
    /// Unary operator that does not have an explicit priority. Unary operators have
    /// higher priority than binary opertors, e.g., `-1^2 == 1`.
    unary_op: Option<fn(T) -> T>,
    /// An operator can also be constant.
    constant: Option<T>,
}

fn unwrap_operator<'a, O>(wrapped_op: &'a Option<O>, repr: &str) -> ExResult<&'a O> {
    wrapped_op.as_ref().ok_or(make_op_not_available_error(repr))
}

impl<'a, T: Copy> Operator<'a, T> {
    fn new(
        repr: &'a str,
        bin_op: Option<BinOp<T>>,
        unary_op: Option<fn(T) -> T>,
        constant: Option<T>,
    ) -> Operator<'a, T> {
        if constant.is_some() {
            if bin_op.is_some() {
                panic!(
                    "Bug! Operators cannot be constant and binary. Check '{}'",
                    repr
                );
            }
            if unary_op.is_some() {
                panic!(
                    "Bug! Operators cannot be constant and unary. Check '{}'.",
                    repr
                );
            }
        }
        Operator {
            repr,
            bin_op,
            unary_op,
            constant,
        }
    }

    /// Creates a binary operator.
    pub fn make_bin(repr: &'a str, bin_op: BinOp<T>) -> Operator<'a, T> {
        Operator::new(repr, Some(bin_op), None, None)
    }
    /// Creates a unary operator.
    pub fn make_unary(repr: &'a str, unary_op: fn(T) -> T) -> Operator<'a, T> {
        Operator::new(repr, None, Some(unary_op), None)
    }
    /// Creates an operator that is either unary or binary based on its positioning in the string to be parsed.
    /// For instance, `-` as defined in [`DefaultOpsFactory`](DefaultOpsFactory) is unary in `-x` and binary
    /// in `2-x`.
    pub fn make_bin_unary(
        repr: &'a str,
        bin_op: BinOp<T>,
        unary_op: fn(T) -> T,
    ) -> Operator<'a, T> {
        Operator::new(repr, Some(bin_op), Some(unary_op), None)
    }
    /// Creates a constant operator. If an operator is constant it cannot be additionally binary or unary.
    pub fn make_constant(repr: &'a str, constant: T) -> Operator<'a, T> {
        Operator::new(repr, None, None, Some(constant))
    }

    pub fn bin(&self) -> ExResult<BinOp<T>> {
        Ok(*unwrap_operator(&self.bin_op, self.repr)?)
    }
    pub fn unary(&self) -> ExResult<fn(T) -> T> {
        Ok(*unwrap_operator(&self.unary_op, self.repr)?)
    }
    pub fn repr(&self) -> &'a str {
        self.repr
    }
    pub fn has_bin(&self) -> bool {
        self.bin_op.is_some()
    }
    pub fn has_unary(&self) -> bool {
        self.unary_op.is_some()
    }
    pub fn constant(&self) -> Option<T> {
        self.constant
    }
}

pub type VecOfUnaryFuncs<T> = SmallVec<[fn(T) -> T; N_UNARYOPS_OF_DEEPEX_ON_STACK]>;

/// Container of unary operators of one expression
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct UnaryOp<T> {
    funcs_to_be_composed: VecOfUnaryFuncs<T>,
}

impl<T> UnaryOp<T> {
    /// Applies unary operators one after the other starting with the last.
    /// # Arguments
    ///
    /// * `x` - number the unary operators are applied to
    ///
    pub fn apply(&self, x: T) -> T {
        let mut result = x;
        // rev, since the last uop is applied first by convention
        for uo in self.funcs_to_be_composed.iter().rev() {
            result = uo(result);
        }
        result
    }

    pub fn append_front(&mut self, other: &mut UnaryOp<T>) {
        self.funcs_to_be_composed = other
            .funcs_to_be_composed
            .iter()
            .chain(self.funcs_to_be_composed.iter())
            .map(|f| *f)
            .collect::<SmallVec<_>>();
    }

    pub fn len(&self) -> usize {
        self.funcs_to_be_composed.len()
    }

    pub fn new() -> Self {
        Self {
            funcs_to_be_composed: smallvec![],
        }
    }

    pub fn from_vec(v: VecOfUnaryFuncs<T>) -> Self {
        Self {
            funcs_to_be_composed: v,
        }
    }

    pub fn clear(&mut self) {
        self.funcs_to_be_composed.clear();
    }
}

/// A binary operator that consists of a function pointer, a priority, and a commutativity-flag.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct BinOp<T> {
    /// Implementation of the binary operation, e.g., `|a, b| a * b` for multiplication.
    pub apply: fn(T, T) -> T,
    /// Priority of the binary operation. A binary operation with a
    /// higher number will be executed first. For instance, in a sane world `*`
    /// has a higher priority than `+`. However, in Exmex land you could also define
    /// this differently.
    pub prio: i32,
    /// True if this is a commutative operator such as `*` or `+`, false if not such as `-`, `/`, or `^`.
    /// Commutativity is used to compile sub-expressions of numbers correctly.
    pub is_commutative: bool,
}

/// To use custom operators one needs to create a factory that implements this trait.
/// In this way, we make sure that we can deserialize expressions with
/// [`serde`](docs.rs/serde) with the correct operators based on the type.
///
/// # Example
///
/// ```rust
/// use exmex::{BinOp, MakeOperators, Operator};
/// #[derive(Clone)]
/// struct SomeOpsFactory;
/// impl MakeOperators<f32> for SomeOpsFactory {
///     fn make<'a>() -> Vec<Operator<'a, f32>> {    
///         vec![
///             Operator::make_bin_unary(
///                 "-",
///                 BinOp {
///                     apply: |a, b| a - b,
///                     prio: 0,
///                     is_commutative: false,
///                 },
///                 |a| (-a),
///             ),
///             Operator::make_unary("sin", |a| a.sin())
///         ]
///     }
/// }
/// ```
pub trait MakeOperators<T: Copy>: Clone {
    /// Function that creates a vector of operators.
    fn make<'a>() -> Vec<Operator<'a, T>>;
}

/// Factory of default operators for floating point values.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct DefaultOpsFactory<T: Float> {
    dummy: PhantomData<T>,
}

impl<T: Float> MakeOperators<T> for DefaultOpsFactory<T> {
    /// Returns the default operators.
    fn make<'a>() -> Vec<Operator<'a, T>> {
        vec![
            Operator::make_bin(
                "^",
                BinOp {
                    apply: |a, b| a.powf(b),
                    prio: 4,
                    is_commutative: false,
                },
            ),
            Operator::make_bin(
                "*",
                BinOp {
                    apply: |a, b| a * b,
                    prio: 2,
                    is_commutative: true,
                },
            ),
            Operator::make_bin(
                "/",
                BinOp {
                    apply: |a, b| a / b,
                    prio: 3,
                    is_commutative: false,
                },
            ),
            Operator::make_bin_unary(
                "+",
                BinOp {
                    apply: |a, b| a + b,
                    prio: 0,
                    is_commutative: true,
                },
                |a| a,
            ),
            Operator::make_bin_unary(
                "-",
                BinOp {
                    apply: |a, b| a - b,
                    prio: 1,
                    is_commutative: false,
                },
                |a| -a,
            ),
            Operator::make_unary("signum", |a| a.signum()),
            Operator::make_unary("sin", |a| a.sin()),
            Operator::make_unary("cos", |a| a.cos()),
            Operator::make_unary("tan", |a| a.tan()),
            Operator::make_unary("asin", |a| a.asin()),
            Operator::make_unary("acos", |a| a.acos()),
            Operator::make_unary("atan", |a| a.atan()),
            Operator::make_unary("sinh", |a| a.sinh()),
            Operator::make_unary("cosh", |a| a.cosh()),
            Operator::make_unary("tanh", |a| a.tanh()),
            Operator::make_unary("floor", |a| a.floor()),
            Operator::make_unary("ceil", |a| a.ceil()),
            Operator::make_unary("trunc", |a| a.trunc()),
            Operator::make_unary("fract", |a| a.fract()),
            Operator::make_unary("exp", |a| a.exp()),
            Operator::make_unary("sqrt", |a| a.sqrt()),
            Operator::make_unary("log", |a| a.ln()),
            Operator::make_unary("log2", |a| a.log2()),
            Operator::make_constant("PI", T::from(std::f64::consts::PI).unwrap()),
            Operator::make_constant("π", T::from(std::f64::consts::PI).unwrap()),
            Operator::make_constant("E", T::from(std::f64::consts::E).unwrap()),
        ]
    }
}

/// This macro creates an operator factory struct that implements the trait
/// [`MakeOperators`](MakeOperators). You have to pass the name of the struct
/// as first, the type of the operands as second, and the [`Operator`](Operator)s as
/// third to n-th argument.
///
/// # Example
///
/// The following snippet creates a struct that can be used as in [`FlatEx<_, MyOpsFactory>`](crate::FlatEx).
/// ```
/// use exmex::{MakeOperators, Operator, ops_factory};
/// ops_factory!(
///     MyOpsFactory,  // name of struct
///     f32,           // data type of operands
///     Operator::make_unary("log", |a| a.ln()),
///     Operator::make_unary("log2", |a| a.log2())
/// );
/// ```
#[macro_export]
macro_rules! ops_factory {
    ($name:ident, $T:ty, $( $ops:expr ),*) => {
        #[derive(Clone)]
        struct $name;
        impl MakeOperators<$T> for $name {
            fn make<'a>() -> Vec<Operator<'a, $T>> {
                vec![$($ops,)*]
            }
        }
    }
}