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
use derive_new::new;
use schemars::JsonSchema;
use std::fmt;
use utoipa::ToSchema;
pub mod operator;
use operator::Operator;
use serde::{Deserialize, Serialize};
//use crate::ast::MathExpression::SummationOp;

/// Represents identifiers such as variables, function names, constants.
/// E.g. x , sin, n
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct Mi(pub String);

/// Represents groups of any subexpressions
/// E.g. For a given expression: 2x+4 -->  2 and x are grouped together
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct Mrow(pub Vec<MathExpression>);

#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub enum Type {
    Integer,
    Rational,
    Real,
    Complex,
    ComplexPolar,
    ComplexCartesian,
    Constant,
    Function,
    Vector,
    List,
    Set,
    Matrix,
}

/// Represents content identifiers such that variables can be have type attribute
/// to specify what it represents. E.g. function, vector, real,...
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct Ci {
    pub r#type: Option<Type>,
    pub content: Box<MathExpression>,
    pub func_of: Option<Vec<Ci>>,
    pub notation: Option<VectorNotation>,
}

/// Vector notation call for Ci being bold or an arrow
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub enum VectorNotation {
    Bold,
    Arrow,
}

/// Represents the differentiation operator `diff` for functions or expresions `func`
/// E.g. df/dx
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct Differential {
    pub diff: Box<MathExpression>,
    pub func: Box<MathExpression>,
}

/// Represents sum operator with terms that are summed over
/// E.g. sum_{i=1}^{K} f(x_i)
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct SummationMath {
    pub op: Box<MathExpression>,
    pub func: Box<MathExpression>,
}

/// Represents expoenential operator with terms that are in the exponential
/// E.g. exp( x(y-z) )
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct ExpMath {
    pub op: Box<MathExpression>,
    pub func: Box<MathExpression>,
}

/// Integral operation represents integral over math expressions
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct Integral {
    pub op: Box<MathExpression>,
    pub integrand: Box<MathExpression>,
    pub integration_variable: Box<MathExpression>,
}

/// Represents Hat operator and the contents the hat operator is being applied to.
/// E.g. f \hat{x}, where `op` will be \hat{x}, `comp` with be the contents
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct HatComp {
    pub op: Box<MathExpression>,
    pub comp: Box<MathExpression>,
}

/// Laplacian operator of vector calculus which takes in argument `comp`.
/// E.g. ∇^2 f
#[derive(
    Debug, Ord, PartialOrd, PartialEq, Eq, Clone, Hash, new, Deserialize, Serialize, JsonSchema,
)]
pub struct LaplacianComp {
    pub op: Box<MathExpression>,
    pub comp: Ci,
}

/// Handles ↓  such that {comp}↓_{sub}^{sup} can parse
#[derive(
    Debug,
    Ord,
    PartialOrd,
    PartialEq,
    Eq,
    Clone,
    Hash,
    new,
    Deserialize,
    Serialize,
    ToSchema,
    JsonSchema,
)]
pub struct DownArrow {
    pub sub: Option<Box<MathExpression>>,
    pub sup: Option<Box<MathExpression>>,
    pub comp: Box<MathExpression>,
}

/// The MathExpression enum is not faithful to the corresponding element type in MathML 3
/// (https://www.w3.org/TR/MathML3/appendixa.html#parsing_MathExpression)
#[derive(
    Debug,
    PartialOrd,
    Ord,
    PartialEq,
    Eq,
    Clone,
    Hash,
    Default,
    new,
    Deserialize,
    Serialize,
    ToSchema,
    JsonSchema,
)]
pub enum MathExpression {
    Mi(Mi),
    Mo(Operator),
    /// Represents numeric literals such as integers, decimals
    Mn(String),
    /// Represents square root elements
    Msqrt(Box<MathExpression>),
    Mrow(Mrow),
    /// Represents the fraction of expressions where first argument is numerator content and second argument is denominator content
    Mfrac(Box<MathExpression>, Box<MathExpression>),
    /// Represents expressions where first argument is the base and second argument is the superscript
    Msup(Box<MathExpression>, Box<MathExpression>),
    /// Represents expressions where first argument is the base and second argument is the subscript
    Msub(Box<MathExpression>, Box<MathExpression>),
    /// Represents expressions where first argument is the base and second argument is the undersubscript
    Munder(Box<MathExpression>, Box<MathExpression>),
    /// Represents expressions where first argument is the base and second argument is the oversubscript
    Mover(Box<MathExpression>, Box<MathExpression>),
    /// Represents expressions where first argument is the base, second argument is the subscript, third argument is the superscript
    Msubsup(
        Box<MathExpression>,
        Box<MathExpression>,
        Box<MathExpression>,
    ),
    /// Represents arbitrary text
    Mtext(String),
    /// Represents how elements can make changes to their style. E.g. displaystyle
    Mstyle(Vec<MathExpression>),
    /// Represents empty element with blanck space
    Mspace(String),
    /// Handles <mo .../>
    MoLine(String),
    Ci(Ci),
    Differential(Differential),
    SummationMath(SummationMath),
    AbsoluteSup(Box<MathExpression>, Box<MathExpression>),
    Absolute(Box<MathExpression>, Box<MathExpression>),
    HatComp(HatComp),
    Integral(Integral),
    LaplacianComp(LaplacianComp),
    /// Represents closed surface integral over contents. E.g. \\oiint_S ∇ \cdot T dS
    SurfaceIntegral(Box<MathExpression>),
    /// ↓ as an operator e.g. I↓ indicates downward diffuse radiative fluxes per unit indcident flux
    DownArrow(DownArrow),
    Minimize(Box<MathExpression>, Vec<MathExpression>),
    ExpMath(ExpMath),
    #[default]
    None,
}

impl fmt::Display for MathExpression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MathExpression::Mi(Mi(identifier)) => write!(f, "{}", identifier),
            MathExpression::Ci(Ci {
                r#type: _,
                content,
                func_of: _,
                notation: _,
            }) => write!(f, "{}", content),
            MathExpression::Mn(number) => write!(f, "{}", number),
            MathExpression::Msup(base, superscript) => {
                write!(f, "{base}^{{{superscript}}}")
            }
            MathExpression::Msub(base, subscript) => {
                write!(f, "{base}_{{{subscript}}}")
            }
            MathExpression::Msubsup(base, subscript, superscript) => {
                write!(f, "{base}_{{{subscript}}}^{{{superscript}}}")
            }
            MathExpression::Mo(op) => {
                write!(f, "{}", op)
            }
            MathExpression::Mrow(Mrow(elements)) => {
                for e in elements {
                    write!(f, "{}", e)?;
                }
                Ok(())
            }
            MathExpression::Differential(Differential { diff, func }) => {
                write!(f, "{diff}")?;
                write!(f, "{func}")
            }
            MathExpression::AbsoluteSup(base, superscript) => {
                write!(f, "{:?}", base)?;
                write!(f, "{superscript:?}")
            }
            MathExpression::Mtext(text) => write!(f, "{}", text),
            MathExpression::SummationMath(SummationMath { op, func }) => {
                write!(f, "{op}")?;
                write!(f, "{func}")
            }
            MathExpression::ExpMath(ExpMath { op, func }) => {
                write!(f, "{op}")?;
                write!(f, "{func}")
            }
            MathExpression::HatComp(HatComp { op, comp }) => {
                write!(f, "{op}")?;
                write!(f, "{comp}")
            }
            MathExpression::Integral(Integral {
                op,
                integrand,
                integration_variable,
            }) => {
                write!(f, "{op}")?;
                write!(f, "{integrand}")?;
                write!(f, "{integration_variable}")
            }
            MathExpression::LaplacianComp(LaplacianComp { op, comp }) => {
                write!(f, "{op}(")?;
                write!(f, "{comp})")
            }
            MathExpression::SurfaceIntegral(row) => {
                write!(f, "{row})")
            }
            MathExpression::DownArrow(DownArrow { sub, sup, comp }) => match (sub, sup) {
                (Some(low), Some(up)) => write!(f, "{comp}↓_{{{low}}}^{{{up}}}"),
                (Some(low), None) => write!(f, "{comp}↓_{{{low}}}"),
                (None, Some(up)) => write!(f, "{comp}↓^{{{up}}}"),
                (None, None) => write!(f, "{comp}↓"),
            },
            MathExpression::Minimize(op, row) => {
                for e in row {
                    write!(f, "{}", e)?;
                }
                Ok(())
            }
            expression => write!(f, "{expression:?}"),
        }
    }
}

impl fmt::Display for Ci {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.content)
    }
}

/// The Math struct represents the corresponding element type in MathML 3
/// (https://www.w3.org/TR/MathML3/appendixa.html#parsing_math)
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Math {
    pub content: Vec<MathExpression>,
}