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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
mod display;
use crate::{
context::Context,
function::builtin,
out::{ErrorType, EvalResult},
settings,
token::{
self,
tokentype::{IdentifierType, TokenType},
},
value::Value,
};
#[derive(Debug)]
pub enum Request {
VarDeclaration(String, Box<Expression>),
FuncDeclaration(String, Vec<String>, Box<Expression>),
Evaluation(Box<Expression>),
}
impl Request {
pub fn execute(&self, context: &mut Context) -> EvalResult<Option<Value>> {
match self {
Self::Evaluation(expr) => {
Ok(Some(expr.eval(context, None, 0)?.round(context.rounding)))
}
Self::FuncDeclaration(identifier, params, body) => {
if builtin::reserved_keywords().contains(&&identifier[..]) {
Err(ErrorType::ReservedVarName {
var_name: identifier.clone(),
})
} else {
context.add_function(identifier.clone(), params.clone(), body.clone());
Ok(None)
}
}
Self::VarDeclaration(identifier, expression) => {
if builtin::reserved_keywords().contains(&&identifier[..]) {
Err(ErrorType::ReservedFunctionName {
func_name: identifier.clone(),
})
} else {
context.add_variable(identifier.clone(), expression.clone());
Ok(None)
}
}
}
}
}
/// Every expression variant.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Expression {
/// A binary operation between two expression.
Binary(Box<Expression>, TokenType, Box<Expression>),
/// An unary operation to an expression.
Unary(TokenType, Box<Expression>),
/// A variable.
Var(String),
/// A function call and its parameters.
Func(String, Vec<Box<Expression>>),
/// A literal value.
Literal(Value),
/// A union of values.
Union(Vec<Box<Expression>>),
}
impl Expression {
pub fn eval(
&self,
context: &Context,
scope: Option<&Context>,
depth: u32,
) -> EvalResult<Value> {
let depth = depth + 1;
// Check depth limit
match context.depth_limit {
settings::DepthLimit::Limit(max) => {
if depth >= max {
return Err(ErrorType::RecursionDepthLimitReached { limit: max });
}
}
settings::DepthLimit::NoLimit => (),
}
match self {
Self::Binary(left_expr, token_type, right_expr) => {
let left_value = (**left_expr).eval(context, scope, depth)?;
let right_value = (**right_expr).eval(context, scope, depth)?;
Ok(match token_type {
// Sum
TokenType::Plus => Value::add(left_value, right_value)?,
// Subtraction
TokenType::Minus => Value::sub(left_value, right_value)?,
// Multiplication
TokenType::Star => Value::mul(left_value, right_value)?,
// Division
TokenType::Slash => Value::div(left_value, right_value)?,
// Exponentiation
TokenType::Caret => Value::exponentiation(left_value, right_value)?,
// Modulo
TokenType::Percentage => Value::modulo(left_value, right_value)?,
// Less than
TokenType::LessThan => Value::less_than(left_value, right_value)?,
// Greater than
TokenType::GreaterThan => Value::greater_than(left_value, right_value)?,
// Less or equal to
TokenType::LessOrEqualTo => Value::less_or_equal_to(left_value, right_value)?,
// Greater or equal to
TokenType::GreaterOrEqualTo => {
Value::greater_or_equal_to(left_value, right_value)?
}
// Logical AND
TokenType::DoubleAnd => Value::logical_and(left_value, right_value)?,
// Logical OR
TokenType::DoubleOr => Value::logical_or(left_value, right_value)?,
// Equal to
TokenType::DoubleEqual => Value::equal_to(left_value, right_value)?,
// Not equal to
TokenType::NotEqual => Value::not_equal_to(left_value, right_value)?,
_ => return Err(ErrorType::InvalidTokenPosition { token: *token_type }),
})
}
Self::Unary(token_type, expr) => Ok(match token_type {
// Negate
TokenType::Minus => Value::negate(expr.eval(context, scope, depth)?)?,
// Not
TokenType::Exclamation => Value::not(expr.eval(context, scope, depth)?)?,
_ => return Err(ErrorType::InvalidTokenPosition { token: *token_type }),
}),
Self::Union(expressions) => {
let mut vec = vec![];
for expr in expressions {
vec.push(expr.eval(context, scope, depth)?);
}
if vec.len() == 1 {
Ok(vec[0].clone())
} else {
Ok(Value::Vector(vec))
}
}
Self::Var(identifier) => {
// Check built-in vars
if let Some(var) = builtin::get_built_in_const(identifier) {
return Ok(var);
}
// Check scope vars
if let Some(c) = scope {
if let Some(expr) = c.get_var(identifier) {
return Ok(expr.eval(context, scope, depth)?);
}
}
// Check context
if let Some(expr) = context.get_var(identifier) {
return Ok(expr.eval(context, scope, depth)?);
}
// Try to split the identifier, as it might have not been interpreted correctly
// in a function declaration, where function parameters were not know at the
// time of "tokenization".
let mut joined_context = context.clone();
// Create a new context with all the data.
joined_context.join_with(context);
if let Some(c) = scope {
joined_context.join_with(&c);
}
let identifiers =
token::split_into_identifiers(identifier.clone(), &joined_context);
let mut product = Value::Float(1.0);
let mut valid = true;
let mut argument = Option::None;
// Iterate over results
for (i, i_type) in identifiers {
match i_type {
IdentifierType::Unknown => {
// Invalidate result if it still unknown
valid = false;
break;
}
IdentifierType::Function => {
// use the following identifier as argument
// if this is the last identifier, return an error
argument = Option::Some(i);
}
IdentifierType::Var => {
if let Some(func_ident) = argument {
product = Value::mul(
product,
Self::Func(func_ident, vec![Box::new(Self::Var(i))])
.eval(context, scope, depth)?,
)?;
argument = Option::None;
} else {
product =
Value::mul(product, Self::Var(i).eval(context, scope, depth)?)?;
}
}
}
}
if valid && argument == Option::None {
Ok(product)
} else {
Err(ErrorType::UnknownVar {
var_name: identifier.clone(),
})
}
}
Self::Func(identifier, arguments) => {
// Check built-in functions
if let Some(func) = builtin::get_built_in_function(identifier) {
return Ok(func.call(arguments, context, scope, depth)?);
}
// Check user-defined ones
if let Some((names, body)) = context.get_function(&identifier) {
let mut inner_scope = {
let mut cont = context.clone();
// Retrieve the parameters values
let params = match value_to_params(
names,
&Expression::Union(arguments.clone()).eval(context, scope, depth)?,
) {
Ok(value) => value,
Err(err) => {
return match err {
ErrorType::WrongFunctionArgumentsAmount {
func_name: _,
expected,
given,
} => Err(ErrorType::WrongFunctionArgumentsAmount {
func_name: identifier.clone(),
expected,
given,
}),
other => Err(other),
}
}
};
for (name, val) in params {
cont.add_variable(name, Box::new(Expression::Literal(val)))
}
cont
};
match scope {
Some(cont) => inner_scope.join_with(cont),
None => (),
};
return Ok(body.eval(context, Some(&inner_scope), depth)?);
}
// Try to split the identifier, as it might have not been interpreted correctly
// in a function declaration, where function parameters were not know at the
// time of "tokenization".
let mut joined_context = context.clone();
// Create a new context with all the data.
joined_context.join_with(context);
if let Some(c) = scope {
joined_context.join_with(&c);
}
let identifiers =
token::split_into_identifiers(identifier.clone(), &joined_context);
let mut product = Value::Float(1.0);
let mut valid = true;
let mut argument = Option::None;
let mut last_i = identifier.clone();
let mut last_i_type = IdentifierType::Unknown;
// Iterate over results
for (i, i_type) in identifiers {
match i_type {
IdentifierType::Unknown => {
// Invalidate result if it still unknown
valid = false;
break;
}
IdentifierType::Function => {
// use the following identifier as argument
// if this is the last identifier, return an error
argument = Option::Some(i.clone());
}
IdentifierType::Var => {
if let Some(func_ident) = argument {
product = Value::mul(
product,
Self::Func(func_ident, vec![Box::new(Self::Var(i.clone()))])
.eval(context, scope, depth)?,
)?;
argument = Option::None;
} else {
product = Value::mul(
product,
Self::Var(i.clone()).eval(context, scope, depth)?,
)?;
}
}
}
(last_i, last_i_type) = (i.clone(), i_type);
}
// If there are no unknown token and last token is a function multiply
// the product of all the previous vars/functions and the result of the
// current one.
if valid && last_i_type == IdentifierType::Function {
Value::mul(
product,
Self::Func(last_i, arguments.clone()).eval(context, scope, depth)?,
)
} else {
Err(ErrorType::UnknownFunction {
func_name: identifier.clone(),
})
}
}
Self::Literal(value) => Ok(value.clone()),
}
}
}
fn value_to_params(names: Vec<String>, value: &Value) -> EvalResult<Vec<(String, Value)>> {
match value {
Value::Vector(vec) => {
if names.len() != vec.len() {
Err(ErrorType::WrongFunctionArgumentsAmount {
func_name: "".to_owned(),
expected: names.len() as u8,
given: vec.len() as u8,
})
} else {
let mut zipped = std::iter::zip(names, vec);
let mut out = vec![];
while let Some((name, val)) = zipped.next() {
out.push((name, val.clone()));
}
Ok(out)
}
}
other => {
if names.len() != 1 {
Err(ErrorType::WrongFunctionArgumentsAmount {
func_name: "".to_owned(),
expected: names.len() as u8,
given: 1,
})
} else {
Ok(vec![(names[0].clone(), other.clone())])
}
}
}
}