vexity 0.0.1

Tiny scripting language for hacking on abstractions of financial markets.
Documentation
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use crate::ast::{BinaryOpKind as Op, Expr, Statement};
use crate::std as vexity_std;
use std::{collections::HashMap, fmt, sync::Arc};

/// A runtime value in the vex interpreter.
///
/// These variants are produced by evaluating expressions
/// and are used for storing variables, passing arguments,
/// and computation on the Rust side.
#[derive(Debug, Clone)]
pub enum VarValue {
    /// A boolean value (true or false)
    Bool(bool),

    /// A UTF-8 string value.
    ///
    /// # Example
    /// ```ignore
    /// "hello 🌍"
    /// ```
    String(String),

    /// A 32-bit signed integer value.
    ///
    /// # Examples
    /// ```ignore
    /// 1
    /// 0
    /// -1
    /// ```
    Int(i32),

    /// A 64-bit floating-point number value.
    ///
    /// # Examples
    /// ```ignore
    /// 3.14
    /// 0.00
    /// -3.14
    /// ```
    Float(f64),

    /// A heterogeneous list of runtime values.
    ///
    /// # Example
    /// ```ignore
    /// [1, 2.0, "foo", true]
    /// ```
    Array(Vec<VarValue>),

    /// A mapping from string keys to runtime values.
    ///
    /// # Example
    /// ```ignore
    /// { "x": 1, "y": 2.0, "label": "point" }
    /// ```
    HashMap(HashMap<String, VarValue>),

    /// A one-argument anonymous function (lambda).
    ///
    /// Lambdas capture a single parameter name and a block of statements.
    /// They can be passed around and invoked via methods like `.map(...)`.
    ///
    /// # Example
    /// ```ignore
    /// |x| x * 2
    /// ```
    Lambda { param: String, body: Vec<Statement> },
}
impl fmt::Display for VarValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            VarValue::Bool(b) => write!(f, "{}", b),
            VarValue::String(s) => write!(f, "{}", s),
            VarValue::Int(v) => write!(f, "{}", v),
            VarValue::Float(v) => write!(f, "{}", v),
            VarValue::Array(arr) => write!(f, "{:?}", arr),
            VarValue::HashMap(map) => {
                write!(f, "{{")?;
                for (i, (k, v)) in map.iter().enumerate() {
                    write!(f, "{}: {}", k, v)?;
                    if i + 1 < map.len() {
                        write!(f, ", ")?;
                    }
                }
                write!(f, "}}")
            }
            VarValue::Lambda { param, body } => write!(f, "|{}| {:?}", param, body),
        }
    }
}

/// Represents a function
pub enum Func {
    /// A native or "built in" vex function
    Builtin(Arc<dyn Fn(Vec<VarValue>) -> VarValue + Send + Sync>),

    /// A user defined "custom" function written in vex
    Script {
        params: Vec<String>,
        body: Vec<Statement>,
    },
}
impl Clone for Func {
    fn clone(&self) -> Self {
        match self {
            Func::Builtin(f) => Func::Builtin(f.clone()),
            Func::Script { params, body } => Func::Script {
                params: params.clone(),
                body: body.clone(),
            },
        }
    }
}

/// The core interpreter state and scope.
///
/// Holds global variable bindings and registered functions
/// (both built-in and user-defined) used to evaluate and
/// execute parsed statements.
pub struct Interpreter {
    /// A mapping of variable names to their current runtime values.
    vars: HashMap<String, VarValue>,

    /// A mapping of function names to their definitions.
    funcs: HashMap<String, Func>,
}
impl Default for Interpreter {
    /// Initialize a default Interpreter instance
    fn default() -> Self {
        Self::new()
    }
}
impl Interpreter {
    /// Create a new Interpreter instance
    pub fn new() -> Self {
        // Intialize the interpreter state with these built
        // in functions from the Vexity standard library.
        let funcs = HashMap::from([
            ("sma".into(), vexity_std::sma()),
            ("ema".into(), vexity_std::ema()),
            ("vwma".into(), vexity_std::vwma()),
            ("lsma".into(), vexity_std::lsma()),
        ]);

        Interpreter {
            vars: HashMap::new(),
            funcs,
        }
    }

    /// Execute a sequence of top level vex statements in order.
    ///
    /// This serves as the main entry point for interpreting parsed programs.
    /// It supports variable bindings, function calls, lambda definitions,
    /// print statements, and user defined function registration.
    pub fn run(&mut self, stmts: Vec<Statement>) {
        for stmt in stmts {
            match stmt {
                Statement::LetExpression { name, value } => {
                    let val = self.eval_expr(value);
                    self.vars.insert(name, val);
                }
                Statement::Expression { value } => {
                    self.eval_expr(value);
                }
                Statement::Print { name } => {
                    let v = self
                        .vars
                        .get(&name)
                        .unwrap_or_else(|| panic!("Variable `{}` not found", name));
                    println!("{}", v);
                }
                Statement::Call { function, args } => {
                    let evaluated = args.into_iter().map(|e| self.eval_expr(e)).collect();
                    self.call_func(&function, evaluated);
                }
                Statement::FunctionDef { name, params, body } => {
                    self.funcs.insert(name, Func::Script { params, body });
                }
            }
        }
    }

    /// Evaluate an expression in the global scope.
    ///
    /// This method is used to evaluate all forms of expressions
    /// supported by Vex, including literals, variables, arrays,
    /// hash maps, field access, function calls, lambdas, method
    /// calls, and binary operations.
    fn eval_expr(&mut self, expr: Expr) -> VarValue {
        match expr {
            Expr::Boolean(b) => VarValue::Bool(b),
            Expr::String(s) => VarValue::String(s),
            Expr::Integer(i) => VarValue::Int(i),
            Expr::Float(f) => VarValue::Float(f),
            Expr::Array(items) => {
                VarValue::Array(items.into_iter().map(|e| self.eval_expr(e)).collect())
            }
            Expr::HashMap(map) => VarValue::HashMap(
                map.into_iter()
                    .map(|(k, v)| (k, self.eval_expr(v)))
                    .collect(),
            ),
            Expr::Identifier(n) => self
                .vars
                .get(&n)
                .cloned()
                .unwrap_or_else(|| panic!("Variable `{}` not found", n)),
            Expr::Field { target, name } => {
                if let VarValue::HashMap(mut m) = self.eval_expr(*target) {
                    m.remove(&name)
                        .unwrap_or_else(|| panic!("key `{}` not found", name))
                } else {
                    panic!("field access on non-hashmap")
                }
            }
            Expr::BinaryOp { lhs, op, rhs } => {
                let l = self.eval_expr(*lhs);
                let r = self.eval_expr(*rhs);
                self.eval_binary(l, op, r)
            }
            Expr::Lambda { param, body } => VarValue::Lambda { param, body },
            Expr::Call { function, args } => {
                let evaluated = args.into_iter().map(|e| self.eval_expr(e)).collect();
                self.call_func(&function, evaluated)
            }
            Expr::MethodCall {
                target,
                method,
                arg,
            } => {
                let tgt = self.eval_expr(*target);
                self.eval_method_call(tgt, &method, *arg)
            }
        }
    }

    /// Evaluate binary numeric operations.
    fn eval_binary(&self, l: VarValue, op: Op, r: VarValue) -> VarValue {
        let (a, b) = match (l, r) {
            (VarValue::Int(a), VarValue::Int(b)) => (a as f64, b as f64),
            (VarValue::Int(a), VarValue::Float(b)) => (a as f64, b),
            (VarValue::Float(a), VarValue::Int(b)) => (a, b as f64),
            (VarValue::Float(a), VarValue::Float(b)) => (a, b),
            (x, y) => panic!("Cannot apply {:?} to {:?} and {:?}", op, x, y),
        };
        let res = match op {
            Op::Add => a + b,
            Op::Sub => a - b,
            Op::Mul => a * b,
            Op::Div => a / b,
        };
        if res.fract() == 0.0 {
            VarValue::Int(res as i32)
        } else {
            VarValue::Float(res)
        }
    }

    /// Call a function by name.
    fn call_func(&mut self, name: &str, args: Vec<VarValue>) -> VarValue {
        let func = self
            .funcs
            .get(name)
            .unwrap_or_else(|| panic!("unknown function `{}`", name))
            .clone();
        match func {
            Func::Builtin(f) => f(args),
            Func::Script { params, body } => {
                if params.len() != args.len() {
                    panic!("{} expects {} args, got {}", name, params.len(), args.len());
                }
                let mut scope = self.vars.clone();
                for (p, v) in params.into_iter().zip(args) {
                    scope.insert(p, v);
                }
                self.eval_statements_in_scope(&body, &mut scope)
            }
        }
    }

    /// Evaluate a sequence of statements in a lambda-local scope.
    fn eval_statements_in_scope(
        &mut self,
        stmts: &[Statement],
        scope: &mut HashMap<String, VarValue>,
    ) -> VarValue {
        let mut last = VarValue::Float(0.0);
        for stmt in stmts {
            match stmt {
                Statement::LetExpression { name, value } => {
                    let val = self.eval_expr_in_scope(value, scope);
                    scope.insert(name.clone(), val.clone());
                    last = val;
                }
                Statement::Expression { value } => {
                    last = self.eval_expr_in_scope(value, scope);
                }
                Statement::Call { function, args } => {
                    let evaluated = args
                        .iter()
                        .map(|e| self.eval_expr_in_scope(e, scope))
                        .collect();
                    last = self.call_func(function, evaluated);
                }
                Statement::Print { name } => {
                    let v = scope
                        .get(name)
                        .unwrap_or_else(|| panic!("Variable `{}` not in scope", name));
                    println!("{}", v);
                }
                Statement::FunctionDef { name, params, body } => {
                    self.funcs.insert(
                        name.clone(),
                        Func::Script {
                            params: params.clone(),
                            body: body.clone(),
                        },
                    );
                    last = VarValue::Float(0.0);
                }
            }
        }
        last
    }

    /// Helper to evaluate an expression with a given local scope.
    fn eval_expr_in_scope(&mut self, expr: &Expr, scope: &HashMap<String, VarValue>) -> VarValue {
        match expr {
            Expr::Boolean(b) => VarValue::Bool(*b),
            Expr::String(s) => VarValue::String(s.clone()),
            Expr::Integer(i) => VarValue::Int(*i),
            Expr::Float(f) => VarValue::Float(*f),
            Expr::Array(items) => VarValue::Array(
                items
                    .iter()
                    .map(|e| self.eval_expr_in_scope(e, scope))
                    .collect(),
            ),
            Expr::HashMap(m) => VarValue::HashMap(
                m.iter()
                    .map(|(k, v)| (k.clone(), self.eval_expr_in_scope(v, scope)))
                    .collect(),
            ),
            Expr::Identifier(n) => scope
                .get(n)
                .cloned()
                .or_else(|| self.vars.get(n).cloned())
                .unwrap_or_else(|| panic!("unknown identifier `{}`", n)),
            Expr::Field { target, name } => {
                if let VarValue::HashMap(mut m) = self.eval_expr_in_scope(target, scope) {
                    m.remove(name)
                        .unwrap_or_else(|| panic!("key `{}` not found", name))
                } else {
                    panic!("invalid field target");
                }
            }
            Expr::BinaryOp { lhs, op, rhs } => {
                let l = self.eval_expr_in_scope(lhs, scope);
                let r = self.eval_expr_in_scope(rhs, scope);
                self.eval_binary(l, op.clone(), r)
            }
            Expr::Lambda { param, body } => VarValue::Lambda {
                param: param.clone(),
                body: body.clone(),
            },
            Expr::Call { function, args } => {
                let evaluated = args
                    .iter()
                    .map(|e| self.eval_expr_in_scope(e, scope))
                    .collect();
                self.call_func(function, evaluated)
            }
            Expr::MethodCall {
                target,
                method,
                arg,
            } => {
                let tgt = self.eval_expr_in_scope(target, scope);
                self.eval_method_call(tgt, method, *arg.clone())
            }
        }
    }

    /// Handle array methods like `map` and `for_each`.
    fn eval_method_call(&mut self, target: VarValue, method: &str, arg: Expr) -> VarValue {
        match (target, method) {
            (VarValue::Array(arr), "map") => {
                let mapped = arr
                    .into_iter()
                    .map(|v| self.eval_lambda_callable(&arg, v))
                    .collect();
                VarValue::Array(mapped)
            }
            (VarValue::Array(arr), "for_each") => {
                for v in &arr {
                    let _ = self.eval_lambda_callable(&arg, v.clone());
                }
                // leave the array unchanged
                VarValue::Array(arr)
            }
            (other, m) => panic!("Unsupported method '{}' on {:?}", m, other),
        }
    }

    /// Evaluates a callable expression in the context of a lambda operation.
    fn eval_lambda_callable(&mut self, callable: &Expr, input: VarValue) -> VarValue {
        match callable {
            Expr::Identifier(name) => self.call_func(name, vec![input]),
            Expr::Lambda { param, body } => {
                let mut temp = self.vars.clone();
                temp.insert(param.clone(), input);
                self.eval_statements_in_scope(body, &mut temp)
            }
            other => panic!("map expects a function name or lambda, got {:?}", other),
        }
    }
}