-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltin.rs
More file actions
394 lines (343 loc) · 9.09 KB
/
Copy pathbuiltin.rs
File metadata and controls
394 lines (343 loc) · 9.09 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//!
//! Contains functions to easily retrieve and set built-in functions and constants.
//!
use std::collections::HashMap;
use crate::{
create_func, decl_func, function::Function, function::*, out::ErrorType, read_vec_values,
value::Value, EvalResult, ValueType,
};
use lazy_static::*;
use num::complex::ComplexFloat;
use rand::Rng;
use std::sync::RwLock;
use tuple_conv::RepeatedTuple;
lazy_static! {
#[derive(Debug, Clone)]
static ref CONSTANTS: RwLock<HashMap<&'static str, Value>> = RwLock::new
({
let mut m = HashMap::new();
use std::f64::consts;
// Math constants
m.insert("pi", Value::Float(consts::PI));
m.insert("e", Value::Float(consts::E));
m.insert("tau", Value::Float(consts::TAU));
m.insert("phi", Value::Float(1.618_033_988_749_894));
// Literal values
m.insert("true", Value::Bool(true));
m.insert("false", Value::Bool(false));
m.insert("i", Value::Complex(num::Complex::i()));
m
});
#[derive(Debug, Clone)]
static ref BUILT_IN_FUNCTIONS: RwLock<Vec<Function>> = RwLock::new(vec![
create_func!(min, Arguments::Dynamic),
create_func!(max, Arguments::Dynamic),
create_func!(floor, Arguments::Const(1)),
create_func!(ceil, Arguments::Const(1)),
create_func!(round, Arguments::Const(1)),
create_func!(abs, Arguments::Const(1)),
create_func!(sqrt, Arguments::Const(1)),
create_func!(ln, Arguments::Const(1)),
create_func!(log, Arguments::Const(2)),
create_func!(exp, Arguments::Const(1)),
create_func!(rand, Arguments::Const(2)),
create_func!(branch, Arguments::Const(3)),
create_func!(sin, Arguments::Const(1)),
create_func!(cos, Arguments::Const(1)),
create_func!(tan, Arguments::Const(1)),
create_func!(asin, Arguments::Const(1)),
create_func!(acos, Arguments::Const(1)),
create_func!(atan, Arguments::Const(1)),
create_func!(sinh, Arguments::Const(1)),
create_func!(cosh, Arguments::Const(1)),
create_func!(tanh, Arguments::Const(1)),
create_func!(asinh, Arguments::Const(1)),
create_func!(acosh, Arguments::Const(1)),
create_func!(atanh, Arguments::Const(1)),
create_func!(re, Arguments::Const(1)),
create_func!(im, Arguments::Const(1)),
create_func!(polar, Arguments::Const(1)),
create_func!(arg, Arguments::Const(1)),
create_func!(norm, Arguments::Const(1)),
]);
}
/// Returns `Some(Function)` if the identifier matches some.
pub fn get_built_in_function(identifier: &str) -> Option<Function> {
get_built_in_functions_vec()
.iter()
.find(|x| x.func_identifier == identifier)
.cloned()
}
/// Returns `Some(Value)` if the identifier matches some.
pub fn get_built_in_const(identifier: &str) -> Option<Value> {
get_built_in_consts_map()
.iter()
.find(|&x| x.0 == identifier)
.map(|x| x.1.clone())
}
/// Returns all reserved keywords.
pub fn reserved_keywords<'a>() -> Vec<&'a str> {
[
get_built_in_consts_map()
.iter()
.map(|x| x.0)
.collect::<Vec<&str>>(),
get_built_in_functions_vec()
.iter()
.map(|x| x.func_identifier)
.collect::<Vec<&str>>(),
]
.concat()
}
/// Get a cloned vector of all built-in functions.
pub fn get_built_in_functions_vec() -> Vec<Function> {
BUILT_IN_FUNCTIONS.read().unwrap().iter().cloned().collect()
}
/// Get a cloned vector of all built-in constants.
pub fn get_built_in_consts_map() -> Vec<(&'static str, Value)> {
CONSTANTS
.read()
.unwrap()
.iter()
.map(|x| (x.0.clone(), x.1.clone()))
.collect()
}
/// Add a function to the built-in ones.
pub fn add_built_in_function(func: Function) {
BUILT_IN_FUNCTIONS.write().unwrap().push(func)
}
/// Add a constant to the built-in ones.
///
/// If a constant with the same identifier didn't exist, `None` is returned.
///
/// If it existed, the value is updated and the old value is returned.
pub fn add_built_in_const(identifier: &'static str, value: Value) -> Option<Value> {
CONSTANTS.write().unwrap().insert(identifier, value)
}
/// Removes a built-in function with a matching identifier.
///
/// If a function is found, it is removed and returned, otherwise `None` is returned.
pub fn remove_built_in_function(func_identifier: &str) -> Option<Function> {
if let Some(index) = BUILT_IN_FUNCTIONS
.read()
.unwrap()
.iter()
.position(|x| x.func_identifier == func_identifier)
{
Some(BUILT_IN_FUNCTIONS.write().unwrap().swap_remove(index))
} else {
None
}
}
/// Removes a built-in constant with a matching identifier.
///
/// If a constant is found, it is removed and returned, otherwise `None` is returned.
pub fn remove_built_in_const(const_identifier: &str) -> Option<Value> {
CONSTANTS.write().unwrap().remove(const_identifier)
}
// STD
decl_func!(
min,
FunctionType::Std,
|v| {
let vec = v.as_vector();
let mut min = vec[0].as_float()?;
for elem in vec {
if elem.as_float()? < min {
min = elem.as_float()?;
}
}
Ok(Value::Float(min))
},
ValueType::VectorType
);
decl_func!(
max,
FunctionType::Std,
|v| {
let vec = v.as_vector();
let mut max = vec[0].as_float()?;
for elem in vec {
if elem.as_float()? > max {
max = elem.as_float()?;
}
}
Ok(Value::Float(max))
},
ValueType::VectorType
);
decl_func!(
floor,
FunctionType::Std,
|v| Ok(v.as_float()?.floor()),
ValueType::FloatType
);
decl_func!(
ceil,
FunctionType::Std,
|v| Ok(v.as_float()?.ceil()),
ValueType::FloatType
);
decl_func!(
round,
FunctionType::Std,
|v| Ok(v.as_float()?.round()),
ValueType::FloatType
);
decl_func!(
abs,
FunctionType::Std,
|v: Value| Ok(Value::Float(v.as_complex()?.abs())),
ValueType::ComplexType
);
decl_func!(
sqrt,
FunctionType::Std,
|v: Value| Ok(Value::Complex(v.as_complex()?.sqrt())),
ValueType::ComplexType
);
decl_func!(
ln,
FunctionType::Std,
|v| Ok(v.as_complex()?.ln()),
ValueType::ComplexType
);
decl_func!(
log,
FunctionType::Std,
|v| {
read_vec_values!(v, base, argument);
Ok(argument.as_complex()?.log(base.as_float()?))
},
ValueType::VectorType
);
decl_func!(
exp,
FunctionType::Std,
|v| Ok(v.as_complex()?.exp()),
ValueType::ComplexType
);
decl_func!(
rand,
FunctionType::Std,
|v| {
read_vec_values!(v, min, max);
Ok(Value::Float(
rand::thread_rng().gen_range(min.as_float()?..max.as_float()?),
))
},
ValueType::VectorType
);
// LOGIC
fn branch(arguments: &Vec<Box<Expression>>, context: &Context, depth: u32) -> EvalResult<Value> {
let condition = arguments[0].eval(context, None, depth)?.as_bool()?;
if condition {
Ok(arguments[1].eval(context, None, depth)?)
} else {
Ok(arguments[2].eval(context, None, depth)?)
}
}
// TRIGONOMETRY
decl_func!(
sin,
FunctionType::Trig,
|v| Ok(v.as_complex()?.sin()),
ValueType::ComplexType
);
decl_func!(
cos,
FunctionType::Trig,
|v| Ok(v.as_complex()?.cos()),
ValueType::ComplexType
);
decl_func!(
tan,
FunctionType::Trig,
|v| Ok(v.as_complex()?.tan()),
ValueType::ComplexType
);
decl_func!(
asin,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.asin()),
ValueType::ComplexType
);
decl_func!(
acos,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.acos()),
ValueType::ComplexType
);
decl_func!(
atan,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.atan()),
ValueType::ComplexType
);
decl_func!(
sinh,
FunctionType::Trig,
|v| Ok(v.as_complex()?.sinh()),
ValueType::ComplexType
);
decl_func!(
cosh,
FunctionType::Trig,
|v| Ok(v.as_complex()?.cosh()),
ValueType::ComplexType
);
decl_func!(
tanh,
FunctionType::Trig,
|v| Ok(v.as_complex()?.tanh()),
ValueType::ComplexType
);
decl_func!(
asinh,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.asinh()),
ValueType::ComplexType
);
decl_func!(
acosh,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.acosh()),
ValueType::ComplexType
);
decl_func!(
atanh,
FunctionType::InverseTrig,
|v| Ok(v.as_complex()?.atanh()),
ValueType::ComplexType
);
// COMPLEX
decl_func!(
re,
FunctionType::Std,
|v| Ok(v.as_complex()?.re),
ValueType::ComplexType
);
decl_func!(
im,
FunctionType::Std,
|v| Ok(v.as_complex()?.im),
ValueType::ComplexType
);
decl_func!(
polar,
FunctionType::Std,
|v| Ok(v.as_complex()?.to_polar().to_vec()),
ValueType::ComplexType
);
decl_func!(
arg,
FunctionType::Std,
|v| Ok(v.as_complex()?.arg()),
ValueType::ComplexType
);
decl_func!(
norm,
FunctionType::Std,
|v| Ok(v.as_complex()?.norm()),
ValueType::ComplexType
);