gabelang 3.1.0

A high level, interpretted and garbage collected programming language
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use std::error::Error;
use std::fmt::{ Display, Write };
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::cell::{RefCell, RefMut};
use std::collections::{HashMap, HashSet};

mod built_ins;

/// The stack module contains the Stack class
pub mod stack;

use stack::{Stack, StackError};
use built_ins::BuiltInError;
use crate::ast::{self, join, Assignable, Expression, InfixOp, Literal, PrefixOp, Statement};

/// An Error produced at runtime while executing Gabelang Code
#[derive(Debug)]
pub enum RuntimeError {
    /// Stack errors are generated when trying to manipulate the stack in an invalid way
    /// or when trying to get a variable from the stack that does not exist
    StackError(StackError),
    /// Built In errors are generated when trying to use a BuiltIn function incorrectly
    BuiltInError(BuiltInError),
    /// Invalid Array Index errors are generated when trying to index an array
    /// by a non integer value
    InvalidArrayIndex,
    /// Invalid Object Index errors are generated when trying to index an object by 
    /// something other than a string
    InvalidObjectIndex,
    /// Invalid Index Target errors are generated when trying to index a value that
    /// is neither an array or an object
    InvalidIndexTarget,
    /// Invalid Prop Target errors are generated when trying to use object property syntax on
    /// a value that is not an object
    InvalidPropTarget,
    /// Invalid Prefix Target errors are generated when trying to use a prefix operand
    /// incorrectly
    InvalidPrefixTarget,
    /// Invalid Infix Target errors are generated when trying to use an infix operand
    /// incorrectly
    InvalidInfixTarget,
    /// Invalid Function Call Target errors are generated when trying to use function call
    /// syntax on a value that is not a function
    InvalidFunctionCallTarget,
}

impl From<StackError> for RuntimeError {
    fn from(err: StackError) -> Self {
        Self::StackError(err)
    }
}

impl From<BuiltInError> for RuntimeError {
    fn from(err: BuiltInError) -> Self {
        Self::BuiltInError(err)
    }
}

impl Display for RuntimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Runtime Error: ")?;
        match self {
            Self::StackError(err) => write!(f, "Stack Error: {}", err),
            Self::BuiltInError(err) => write!(f, "BuiltInError: {}", err),
            Self::InvalidArrayIndex => f.write_str("Invalid Array Index"),
            Self::InvalidPropTarget => f.write_str("Invalid Object Property Target"),
            Self::InvalidObjectIndex => f.write_str("Invalid Object Index"),
            Self::InvalidIndexTarget => f.write_str("Invalid Index Target"),
            Self::InvalidInfixTarget => f.write_str("Invalid Infix Target"),
            Self::InvalidPrefixTarget => f.write_str("Invalid Prefix Target"),
            Self::InvalidFunctionCallTarget => f.write_str("Invalid Function Call Target")
        }
    }
}

impl Error for RuntimeError {}

/// A runtime result is a result produced at runtime that can cause a runtime error
pub type RuntimeResult<T> = Result<T, RuntimeError>;

/// An isolated runtime environment for a gabelang program
pub struct Runtime {
    /// The runtime's global stack is the stack at the current instruction
    global_stack: Stack,
    loaded_stack: Option<Stack>,
    built_ins: HashMap<String, Rc<dyn built_ins::BuiltIn>>,
}

impl Runtime {
    /// Creates a new environment with no variables set and with built_in functions like len
    pub fn new() -> Self {
        let built_ins = built_ins::load_built_ins();
        let global_stack = Stack::new();
        let loaded_stack = None;
        Self { built_ins, loaded_stack, global_stack }
    }

    /// Resets the stack of the runtime
    pub fn reset_stack(&mut self) {
        self.global_stack = Stack::new();
    }

    /// Runs a program or statement on the global stack
    pub fn run_program(&mut self, program: &Vec<ast::Statement>) -> RuntimeResult<GabrValue> {
        self.eval_program(program)
    }

    /// Runs a gabelang program from an ast that must be generated by the gabelang Parser 
    ///
    /// When evaluating a program using eval_program_with_new_scope it also creates a new stack frame in order to isolate all variables declared in the program
    ///
    /// This means that if it is called multiple times it will "forget" all variables and functions
    /// declared in previous eval_program calls.
    ///
    /// To run a program without creating a new stack frame look for [Self::eval_program]
    ///
    /// To run a statement without creating a new stack frame look for [Self::eval_statement]
    fn eval_program_with_new_scope(&mut self, program: &Vec<ast::Statement>) -> RuntimeResult<GabrValue> {
        let mut result = GabrValue::new(ObjectInner::NULL.as_object(), false);
        self.current_context().push_scope();
        for statement in program.iter() {
            result = self.eval_statement(statement)?;
            if result.returning {
                self.current_context().pop_scope()?;
                return Ok(result)
            }
        }
        self.current_context().pop_scope()?;
        Ok(result)
    }

    /// Runs a gabelang program from an ast that must be generated by the gabelang Parser 
    ///
    /// When evaluating a program using eval_program it uses the existing stack frame so it will
    /// "remember" previous programs run
    ///
    /// To run a program in a new stack frame look for [Self::eval_program_with_new_scope]
    ///
    /// To run a single statement look for [Self::eval_statement]
    fn eval_program(&mut self, program: &Vec<ast::Statement>) -> RuntimeResult<GabrValue> {
        let mut result = GabrValue::new(ObjectInner::NULL.as_object(), false); 
        for statement in program.iter() {
            result = self.eval_statement(statement)?;
            if result.returning {
                return Ok(result)
            }
        }
        Ok(result)
    }

    fn get_built_in(&self, name: String) -> Option<Rc<dyn built_ins::BuiltIn>> {
        self.built_ins.get(&name).map(|bi| bi.clone())
    }

    fn load_params(&mut self, params: Vec<(String, Object)>) -> RuntimeResult<()> {
        for (name, val) in params {
            self.current_context().create_var(name, val)?;
        }
        Ok(())
    }

    fn get_assignable(&mut self, assignable: &Assignable) -> RuntimeResult<Object> {
        match assignable {
            Assignable::Var(var) => Ok(self.current_context().get_var(&var)?),
            Assignable::PropIndex { obj, index } => {
                let index = self.eval_expression(index)?;
                let index: &ObjectInner = &index.inner();
                match &mut self.get_assignable(obj)?.inner() as &mut ObjectInner {
                    ObjectInner::ARRAY(arr) => {
                        if let ObjectInner::NUMBER(num) = index {
                            if *num < 0 {
                                return Err(RuntimeError::InvalidArrayIndex);
                            }
                            let num = *num as usize;
                            if (num) < arr.len() {
                                Ok(arr[num].clone())
                            } else {
                                Err(RuntimeError::InvalidArrayIndex)
                            }
                        } else {
                            Err(RuntimeError::InvalidArrayIndex)
                        }
                    },
                    ObjectInner::OBJECT(obj) => {
                        if let ObjectInner::STRING(prop) = index {
                            Ok(obj.get(prop).map(|obj| obj.clone()).unwrap_or(ObjectInner::NULL.as_object()))
                        } else {
                            Err(RuntimeError::InvalidObjectIndex)
                        }
                    },
                    _ => Err(RuntimeError::InvalidIndexTarget)
                }
            },
            Assignable::ObjectProp { obj, prop } => {
                let obj = self.get_assignable(obj)?;
                let obj: &ObjectInner = &obj.inner();
                if let ObjectInner::OBJECT(obj) = obj {
                    // Undefined object properties are retrieved as NULL
                    Ok(obj.get(prop).map(|obj| obj.clone()).unwrap_or(ObjectInner::NULL.as_object()))
                } else {
                    Err(RuntimeError::InvalidPropTarget)
                }
            }
        }
    }

    fn set_assignable(&mut self, assignable: &Assignable, val: Object) -> RuntimeResult<()> {
        match assignable {
            Assignable::Var(var) => {
                Ok(self.current_context().set_var(&var, val)?)
            },
            Assignable::PropIndex { obj, index } => {
                let index = self.eval_expression(index)?;
                let index: &ObjectInner = &index.inner();
                match &mut self.get_assignable(obj)?.inner() as &mut ObjectInner {
                    ObjectInner::ARRAY(arr) => {
                        if let ObjectInner::NUMBER(num) = index {
                            if *num < 0 {
                                return Err(RuntimeError::InvalidArrayIndex);
                            }
                            let num = *num as usize;
                            if (num as usize) < arr.len() {
                                arr[num] = val;
                                Ok(())
                            } else if (num) == arr.len() {
                                arr.push(val);
                                Ok(())
                            } else {
                                Err(RuntimeError::InvalidArrayIndex)
                            }
                        } else {
                            Err(RuntimeError::InvalidArrayIndex)
                        }
                    },
                    ObjectInner::OBJECT(obj) => {
                        if let ObjectInner::STRING(prop) = index {
                            obj.insert(prop.clone(), val);
                            Ok(())
                        } else {
                            Err(RuntimeError::InvalidObjectIndex)
                        }
                    },
                    _ => Err(RuntimeError::InvalidIndexTarget)
                }
            }
            Assignable::ObjectProp { obj, prop } => {
                let obj = self.get_assignable(obj)?;
                let obj_mut: &mut ObjectInner = &mut obj.inner();
                if let ObjectInner::OBJECT(obj) = obj_mut {
                    obj.insert(prop.clone(), val);
                    Ok(())
                } else {
                    Err(RuntimeError::InvalidPropTarget)
                }
            }
        }
    }


    /// Evaluates a single gabelang program statement generated by the parser in the environment's context
    fn eval_statement(&mut self, statement: &Statement) -> RuntimeResult<GabrValue> {
        match statement {
            Statement::Expression(expression) => {
                Ok(GabrValue::new(self.eval_expression(expression)?, true))
            },
            Statement::Let { ident, expression } => {
                let val = self.eval_expression(expression)?;
                self.current_context().create_var(ident.clone(), val)?;
                Ok(GabrValue::new(ObjectInner::NULL.as_object(), false))
            },
            Statement::Assign { assignable, expression } => {
                let val = self.eval_expression(expression)?;
                self.set_assignable(assignable, val)?;
                Ok(GabrValue::new(ObjectInner::NULL.as_object(), false))
            },
            Statement::Return(val) => {
                match val.as_ref() {
                    Some(value) => {
                        Ok(GabrValue::new(self.eval_expression(value)?, true))
                    },
                    None => Ok(GabrValue::new(ObjectInner::NULL.as_object(), true))
                }
            },
            Statement::If { cond, body, r#else } => {
                let condition_result = self.eval_expression(cond)?.inner().is_truthy();
                if condition_result {
                    self.eval_program_with_new_scope(body)
                } else {
                    match r#else.as_ref() {
                        Some(else_block) => self.eval_program_with_new_scope(else_block),
                        None => Ok(GabrValue::new(ObjectInner::NULL.as_object(), false))
                    }
                }
            },
            Statement::DoWhile { body, cond } => {
                let mut result;
                loop {
                    result = self.eval_program_with_new_scope(body)?;
                    if result.returning ||
                    !self.eval_expression(cond)?.inner().is_truthy() {
                        break
                    }
                }
                Ok(result)
            },
            Statement::While { cond, body } => {
                let mut result = GabrValue::new(ObjectInner::NULL.as_object(), false);
                while self.eval_expression(cond)?.inner().is_truthy() {
                    result = self.eval_program_with_new_scope(body)?;
                    if result.returning {
                        break;
                    }
                }
                Ok(result)
            },
            Statement::For { init, cond, update, body } => {
                let mut result = GabrValue::new(ObjectInner::NULL.as_object(), false);
                self.current_context().push_scope();
                self.eval_statement(init)?;
                while self.eval_expression(cond)?.inner().is_truthy() {
                    result = self.eval_program_with_new_scope(body)?;
                    self.eval_statement(update)?;
                    if result.returning {
                        break;
                    }
                }
                self.current_context().pop_scope()?;
                Ok(result)
            }
            Statement::FuncDecl(func) => {
                self.current_context().create_func(func.ident.clone(), func.clone())?;
                Ok(GabrValue::new(ObjectInner::NULL.as_object(), false))
            },
        }
    }

    fn eval_expression(&mut self, expression: &Expression) -> RuntimeResult<Object> {
        match expression {
            Expression::Prefix { op, expression } => {
                self.eval_prefix(*op, expression)
            },
            Expression::Infix { op, left, right } => {
                self.eval_infix(*op, left, right)
            },
            Expression::Group(expression) => {
                self.eval_expression(expression)
            },
            Expression::FuncCall { func, params } => {
                self.eval_function_call(func, params)
            },
            Expression::Assignable(assignable) => {
                // When using an assignable as an expression always deep copy it
                Ok(self.get_assignable(assignable)?.inner().clone().as_object())
            },
            Expression::Literal(lit) => {
                match lit {
                    Literal::NumberLit(num) => Ok(ObjectInner::NUMBER(num.clone()).as_object()),
                    Literal::StringLit(string) => Ok(ObjectInner::STRING(string.clone()).as_object()),
                    Literal::Bool(bool) => Ok(ObjectInner::BOOL(*bool).as_object()),
                    Literal::ArrayLit(arr) => {
                        // Create an array of evaluated expressions
                        let arr: RuntimeResult<Vec<Object>> = arr.iter()
                            .map(|v| self.eval_expression(v))
                            .collect();
                        Ok(ObjectInner::ARRAY(arr?).as_object())
                    },
                    Literal::ObjectLit(obj) => {
                        // Create an object
                        let fields: RuntimeResult<HashMap<String, Object>> = obj.iter()
                            .map(|(ident, expression)| Ok((ident.clone(), self.eval_expression(expression)?)))
                            .collect();
                        Ok(ObjectInner::OBJECT(fields?).as_object())
                    }
                }
            }
        }
    }

    fn eval_prefix(&mut self, op: PrefixOp, expression: &Expression) -> RuntimeResult<Object> {
        let expression = self.eval_expression(expression)?;
        match op {
            PrefixOp::Bang => {
                Ok(ObjectInner::BOOL(!expression.inner().is_truthy()).as_object())
            },
            PrefixOp::Neg => {
                if let ObjectInner::NUMBER(val) = *expression.inner() {
                    Ok(ObjectInner::NUMBER(-val).as_object())
                } else {
                    Err(RuntimeError::InvalidPrefixTarget)
                }
            }
        }
    }

    fn eval_infix(&mut self, op: InfixOp, left: &Expression, right: &Expression) -> RuntimeResult<Object> {
        let op1 = self.eval_expression(left)?.inner().clone();
        let op2 = self.eval_expression(right)?.inner().clone();
        let op1 = match op1 {
            ObjectInner::NUMBER(num) => num,
            ObjectInner::BOOL(bool) => bool as i64,
            ObjectInner::STRING(string1) => {
                if let ObjectInner::STRING(string2) = op2 {
                    return Ok(ObjectInner::STRING(string1 + &string2).as_object());
                } else {
                    return Err(RuntimeError::InvalidInfixTarget)
                }
            }
            _ => return Err(RuntimeError::InvalidInfixTarget)
        };
        let op2 = match op2 {
            ObjectInner::NUMBER(num) => num,
            ObjectInner::BOOL(bool) => bool as i64,
            _ => return Err(RuntimeError::InvalidInfixTarget)
        };
        let val = match op {
            InfixOp::Add => op1 + op2,
            InfixOp::Sub => op1 - op2,
            InfixOp::Mult => op1 * op2,
            InfixOp::Div => op1 / op2,
            InfixOp::Eq => {
                if op1 == op2 {
                    1
                } else {
                    0
                }
            },
            InfixOp::NotEq => {
                if op1 != op2 {
                    1
                } else {
                    0
                }
            }
            InfixOp::Gt => {
                if op1 > op2 {
                    1
                } else {
                    0
                }
            },
            InfixOp::Lt => {
                if op1 < op2 {
                    1
                } else {
                    0
                }
            }
        };
        Ok(ObjectInner::NUMBER(val).as_object())
    }

    fn eval_function_call(&mut self, func_locator: &Assignable, params: &Vec<Expression>) -> RuntimeResult<Object> {
        // look in all scopes for a function that matches function name
        let func = self.get_assignable(func_locator).ok();
        if let Some(func) = func {
            let func = &mut *func.inner();
            let func = match func {
                ObjectInner::FUNCTION(func) => func.clone(),
                _ => return Err(RuntimeError::InvalidFunctionCallTarget)
            };
            // Create (parameter, value) list
            let params: RuntimeResult<Vec<(String, Object)>> = func.ast.params.iter()
                .map(|param| param.clone())
                .zip(params.iter())
                .map(|(name, param)| Ok((name, self.eval_expression(param)?)))
                .collect();
            // Hold copy of previous stack for unloading
            let loaded_stack = self.loaded_stack.clone();
            // Load functions stack context
            self.loaded_stack = Some(func.context.clone());
            // Create new scope for parameters
            self.current_context().push_scope();
            self.load_params(params?)?;
            let result = self.eval_program(&func.ast.body)?;
            self.current_context().pop_scope()?;
            // Unload function stack context
            self.loaded_stack = loaded_stack;
            // Function call should not automatically be interpretted as return funcCall(param);
            Ok(result.gabr_object)
        } else {
            let func_name = match func_locator {
                Assignable::Var(ident) => ident,
                _ => return Err(StackError::VariableNotInScope.into()),
            };
            if let Some(built_in) = self.get_built_in(func_name.clone()) {
                let params: RuntimeResult<Vec<(String, Object)>> = built_in.get_params().iter()
                    .map(|param| param.clone())
                    .zip(params.iter())
                    .map(|(name, param)| Ok((name, self.eval_expression(param)?)))
                    .collect();
                // Create new scope for parameters
                self.current_context().push_scope();
                self.load_params(params?)?;
                // Evaluate built in function in new context
                let result = built_in.eval(self)?;
                // Remove param variables scope
                self.current_context().pop_scope()?;
                // Function call should not automatically be interpretted as return funcCall(param);
                Ok(result)
            } else {
                Err(StackError::VariableNotInScope.into())
            }
        }
    }

    /// Gathers the currently loaded variable/stack context, if none is explicitly loaded, it
    /// defaults to the global_context
    pub fn current_context(&mut self) -> &mut Stack {
        return self.loaded_stack.as_mut().unwrap_or(&mut self.global_stack)
    }
}

/// A valid value in the gabelang language
///
/// Could be an integer, array, function, object, or NULL type
#[derive(Clone)]
pub struct GabrValue {
    gabr_object: Object,
    returning: bool,
}

impl GabrValue {
    fn new(gabr_object: Object, returning: bool) -> Self {
        Self { gabr_object, returning }
    }

    /// Checks if the current object is not null
    pub fn is_some(&self) -> bool {
        if let ObjectInner::NULL = *self.gabr_object.inner() {
            false
        } else {
            true
        }
    }
}

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

/// A reference counted gabelang object which can be copied by reference or manipulated
#[derive(Clone, Debug)]
pub struct Object(Rc<RefCell<ObjectInner>>);

impl Object {
    fn inner(&self) -> RefMut<ObjectInner> {
        self.0.borrow_mut()
    }
}

impl PartialEq for Object {
    /// Two objects are equal if they point to the same place in memory
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for Object {}

impl Hash for Object {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let pointer = Rc::as_ptr(&self.0) as usize;
        pointer.hash(state);
    }
}

impl Display for Object {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Creates a static internally mutable map variable on a per thread basis.
        // This variable will stick around between function calls because it is static
        thread_local! {
            static PRINTING: RefCell<HashSet<usize>> = RefCell::new(HashSet::new())
        }
        // cast Rc to a pointer to the underlying object
        let ptr = Rc::as_ptr(&self.0) as usize;
        // If we have seen this object before print "Cycle"
        if PRINTING.with(|printing| printing.borrow().contains(&ptr)) {
            return f.write_str("Cycle");
        }
        // Else indicate that we have seen this object,
        // Print it,
        // And then remove it from the hashset so it doesnt interupt future prints
        PRINTING.with(|printing| printing.borrow_mut().insert(ptr));
        let res = write!(f, "{}", self.0.borrow());
        PRINTING.with(|printing| printing.borrow_mut().remove(&ptr));
        res
    }
}

#[derive(Clone, Debug)]
enum ObjectInner {
    NUMBER(i64),
    STRING(String),
    ARRAY(Vec<Object>),
    FUNCTION(FunctionInner),
    OBJECT(HashMap<String, Object>),
    BOOL(bool),
    NULL
}

impl ObjectInner {
    fn is_truthy(&self) -> bool {
        match self {
            Self::NUMBER(val) => *val != 0,
            Self::NULL => false,
            Self::BOOL(b) if !*b => false,
            _ => true
        }
    }

    fn as_object(self) -> Object {
        Object(Rc::new(RefCell::new(self)))
    }
}

impl Display for ObjectInner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NUMBER(val) => write!(f, "{val}"),
            Self::STRING(string) => f.write_str(string),
            Self::ARRAY(vals) => {
                write!(f, "[{}]", join(vals, ", "))
            },
            Self::OBJECT(obj) => {
                let properties = obj.iter().map(|(key, val)| {
                    let mut output = String::new();
                    write!(output, "\t{key}: {val}").unwrap();
                    output
                }).collect::<Vec<String>>();
                write!(f, "{{\n{}\n}}", join(&properties, "\n"))
            },
            Self::FUNCTION(func) => write!(f, "{func}"),
            Self::BOOL(bool) => write!(f, "{}", bool),
            Self::NULL => f.write_str("null")
        }
    }
}

#[derive(Debug, Clone)]
struct FunctionInner {
    ast: ast::Function,
    context: Stack
}

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