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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Execution of the AST, this is where the interpreter actually runs

#[cfg(test)]
mod tests;

use crate::{
    builtins::{
        array,
        function::{Function as FunctionObject, FunctionBody, ThisMode},
        object::{
            internal_methods_trait::ObjectInternalMethods, Object, ObjectKind, INSTANCE_PROTOTYPE,
            PROTOTYPE,
        },
        property::Property,
        value::{ResultValue, Value, ValueData},
    },
    environment::lexical_environment::{new_declarative_environment, VariableScope},
    realm::Realm,
    syntax::ast::{
        constant::Const,
        node::{FormalParameter, MethodDefinitionKind, Node, PropertyDefinition},
        op::{AssignOp, BinOp, BitOp, CompOp, LogOp, NumOp, UnaryOp},
    },
};
use std::{
    borrow::{Borrow, BorrowMut},
    ops::Deref,
};

/// An execution engine
pub trait Executor {
    /// Make a new execution engine
    fn new(realm: Realm) -> Self;
    /// Run an expression
    fn run(&mut self, expr: &Node) -> ResultValue;
}

/// A Javascript intepreter
#[derive(Debug)]
pub struct Interpreter {
    is_return: bool,
    /// realm holds both the global object and the environment
    pub realm: Realm,
}

fn exec_assign_op(op: &AssignOp, v_a: Value, v_b: Value) -> Value {
    match *op {
        AssignOp::Add => v_a + v_b,
        AssignOp::Sub => v_a - v_b,
        AssignOp::Mul => v_a * v_b,
        AssignOp::Exp => v_a.as_num_to_power(v_b),
        AssignOp::Div => v_a / v_b,
        AssignOp::Mod => v_a % v_b,
        AssignOp::And => v_a & v_b,
        AssignOp::Or => v_a | v_b,
        AssignOp::Xor => v_a ^ v_b,
        AssignOp::Shl => v_a << v_b,
        AssignOp::Shr => v_a << v_b,
    }
}

impl Executor for Interpreter {
    fn new(realm: Realm) -> Self {
        Self {
            realm,
            is_return: false,
        }
    }

    #[allow(clippy::match_same_arms)]
    fn run(&mut self, node: &Node) -> ResultValue {
        match *node {
            Node::Const(Const::Null) => Ok(Value::null()),
            Node::Const(Const::Undefined) => Ok(Value::undefined()),
            Node::Const(Const::Num(num)) => Ok(Value::rational(num)),
            Node::Const(Const::Int(num)) => Ok(Value::integer(num)),
            Node::Const(Const::BigInt(ref num)) => Ok(Value::from(num.clone())),
            // we can't move String from Const into value, because const is a garbage collected value
            // Which means Drop() get's called on Const, but str will be gone at that point.
            // Do Const values need to be garbage collected? We no longer need them once we've generated Values
            Node::Const(Const::String(ref value)) => Ok(Value::string(value.to_string())),
            Node::Const(Const::Bool(value)) => Ok(Value::boolean(value)),
            Node::Block(ref es) => {
                {
                    let env = &mut self.realm.environment;
                    env.push(new_declarative_environment(Some(
                        env.get_current_environment_ref().clone(),
                    )));
                }

                let mut obj = Value::null();
                for e in es.iter() {
                    let val = self.run(e)?;
                    // early return
                    if self.is_return {
                        obj = val;
                        break;
                    }
                    if e == es.last().expect("unable to get last value") {
                        obj = val;
                    }
                }

                // pop the block env
                let _ = self.realm.environment.pop();

                Ok(obj)
            }
            Node::Local(ref name) => {
                let val = self.realm.environment.get_binding_value(name);
                Ok(val)
            }
            Node::GetConstField(ref obj, ref field) => {
                let val_obj = self.run(obj)?;
                Ok(val_obj.borrow().get_field_slice(field))
            }
            Node::GetField(ref obj, ref field) => {
                let val_obj = self.run(obj)?;
                let val_field = self.run(field)?;
                Ok(val_obj
                    .borrow()
                    .get_field_slice(&val_field.borrow().to_string()))
            }
            Node::Call(ref callee, ref args) => {
                let (mut this, func) = match callee.deref() {
                    Node::GetConstField(ref obj, ref field) => {
                        let mut obj = self.run(obj)?;
                        if obj.get_type() != "object" || obj.get_type() != "symbol" {
                            obj = self.to_object(&obj).expect("failed to convert to object");
                        }
                        (obj.clone(), obj.borrow().get_field_slice(field))
                    }
                    Node::GetField(ref obj, ref field) => {
                        let obj = self.run(obj)?;
                        let field = self.run(field)?;
                        (
                            obj.clone(),
                            obj.borrow().get_field_slice(&field.borrow().to_string()),
                        )
                    }
                    _ => (self.realm.global_obj.clone(), self.run(&callee.clone())?), // 'this' binding should come from the function's self-contained environment
                };
                let mut v_args = Vec::with_capacity(args.len());
                for arg in args.iter() {
                    if let Node::Spread(ref x) = arg.deref() {
                        let val = self.run(x)?;
                        let mut vals = self.extract_array_properties(&val).unwrap();
                        v_args.append(&mut vals);
                        break; // after spread we don't accept any new arguments
                    }
                    v_args.push(self.run(arg)?);
                }

                // execute the function call itself
                let fnct_result = self.call(&func, &mut this, &v_args);

                // unset the early return flag
                self.is_return = false;

                fnct_result
            }
            Node::WhileLoop(ref cond, ref expr) => {
                let mut result = Value::undefined();
                while self.run(cond)?.borrow().is_true() {
                    result = self.run(expr)?;
                }
                Ok(result)
            }
            Node::DoWhileLoop(ref body, ref cond) => {
                let mut result = self.run(body)?;
                while self.run(cond)?.borrow().is_true() {
                    result = self.run(body)?;
                }
                Ok(result)
            }
            Node::ForLoop(ref init, ref cond, ref step, ref body) => {
                if let Some(init) = init {
                    self.run(init)?;
                }

                while match cond {
                    Some(cond) => self.run(cond)?.borrow().is_true(),
                    None => true,
                } {
                    self.run(body)?;

                    if let Some(step) = step {
                        self.run(step)?;
                    }
                }

                Ok(Value::undefined())
            }
            Node::If(ref cond, ref expr, None) => Ok(if self.run(cond)?.borrow().is_true() {
                self.run(expr)?
            } else {
                Value::undefined()
            }),
            Node::If(ref cond, ref expr, Some(ref else_e)) => {
                Ok(if self.run(cond)?.borrow().is_true() {
                    self.run(expr)?
                } else {
                    self.run(else_e)?
                })
            }
            Node::Switch(ref val_e, ref vals, ref default) => {
                let val = self.run(val_e)?;
                let mut result = Value::null();
                let mut matched = false;
                for tup in vals.iter() {
                    let cond = &tup.0;
                    let block = &tup.1;
                    if val.strict_equals(&self.run(cond)?) {
                        matched = true;
                        let last_expr = block.last().expect("Block has no expressions");
                        for expr in block.iter() {
                            let e_result = self.run(expr)?;
                            if expr == last_expr {
                                result = e_result;
                            }
                        }
                    }
                }
                if !matched && default.is_some() {
                    result = self.run(
                        default
                            .as_ref()
                            .expect("Could not get default as reference"),
                    )?;
                }
                Ok(result)
            }
            Node::Object(ref properties) => {
                let global_val = &self
                    .realm
                    .environment
                    .get_global_object()
                    .expect("Could not get the global object");
                let obj = Value::new_object(Some(global_val));

                // TODO: Implement the rest of the property types.
                for property in properties.iter() {
                    match property {
                        PropertyDefinition::Property(key, value) => {
                            obj.borrow().set_field_slice(&key.clone(), self.run(value)?);
                        }
                        PropertyDefinition::MethodDefinition(kind, name, func) => {
                            if let MethodDefinitionKind::Ordinary = kind {
                                obj.borrow().set_field_slice(&name.clone(), self.run(func)?);
                            } else {
                                // TODO: Implement other types of MethodDefinitionKinds.
                                unimplemented!("other types of property method definitions.");
                            }
                        }
                        i => unimplemented!("{:?} type of property", i),
                    }
                }

                Ok(obj)
            }
            Node::ArrayDecl(ref arr) => {
                let array = array::new_array(self)?;
                let mut elements = Vec::new();
                for elem in arr.iter() {
                    if let Node::Spread(ref x) = elem.deref() {
                        let val = self.run(x)?;
                        let mut vals = self.extract_array_properties(&val).unwrap();
                        elements.append(&mut vals);
                        continue; // Don't push array after spread
                    }
                    elements.push(self.run(elem)?);
                }
                array::add_to_array_object(&array, &elements)?;
                Ok(array)
            }
            // <https://tc39.es/ecma262/#sec-createdynamicfunction>
            Node::FunctionDecl(ref name, ref args, ref expr) => {
                let val = self.create_function(args.clone(), expr, ThisMode::NonLexical);
                // Set the name and assign it in the current environment

                val.set_field_slice("name", Value::from(name.clone()));
                self.realm.environment.create_mutable_binding(
                    name.clone(),
                    false,
                    VariableScope::Function,
                );

                self.realm.environment.initialize_binding(name, val.clone());

                Ok(val)
            }
            // <https://tc39.es/ecma262/#sec-createdynamicfunction>
            Node::FunctionExpr(ref name, ref args, ref expr) => {
                let val = self.create_function(args.clone(), expr, ThisMode::NonLexical);

                if let Some(name) = name {
                    val.set_field_slice("name", Value::from(name.clone()));
                }

                Ok(val)
            }
            Node::ArrowFunctionDecl(ref args, ref expr) => {
                Ok(self.create_function(args.clone(), expr, ThisMode::Lexical))
            }
            Node::BinOp(BinOp::Num(ref op), ref a, ref b) => {
                let v_a = self.run(a)?;
                let v_b = self.run(b)?;
                Ok(match *op {
                    NumOp::Add => v_a + v_b,
                    NumOp::Sub => v_a - v_b,
                    NumOp::Mul => v_a * v_b,
                    NumOp::Exp => v_a.as_num_to_power(v_b),
                    NumOp::Div => v_a / v_b,
                    NumOp::Mod => v_a % v_b,
                })
            }
            Node::UnaryOp(ref op, ref a) => {
                let v_a = self.run(a)?;
                Ok(match *op {
                    UnaryOp::Minus => -v_a,
                    UnaryOp::Plus => Value::from(v_a.to_number()),
                    UnaryOp::IncrementPost => {
                        let ret = v_a.clone();
                        self.set_value(a, Value::from(v_a.to_number() + 1.0))?;
                        ret
                    }
                    UnaryOp::IncrementPre => {
                        self.set_value(a, Value::from(v_a.to_number() + 1.0))?
                    }
                    UnaryOp::DecrementPost => {
                        let ret = v_a.clone();
                        self.set_value(a, Value::from(v_a.to_number() - 1.0))?;
                        ret
                    }
                    UnaryOp::DecrementPre => {
                        self.set_value(a, Value::from(v_a.to_number() - 1.0))?
                    }
                    UnaryOp::Not => !v_a,
                    UnaryOp::Tilde => {
                        let num_v_a = v_a.to_number();
                        // NOTE: possible UB: https://github.com/rust-lang/rust/issues/10184
                        Value::from(if num_v_a.is_nan() {
                            -1
                        } else {
                            !(num_v_a as i32)
                        })
                    }
                    UnaryOp::Void => Value::undefined(),
                    UnaryOp::Delete => match a.deref() {
                        Node::GetConstField(ref obj, ref field) => {
                            Value::boolean(self.run(obj)?.remove_property(field))
                        }
                        Node::GetField(ref obj, ref field) => Value::boolean(
                            self.run(obj)?
                                .remove_property(&self.run(field)?.to_string()),
                        ),
                        Node::Local(_) => Value::boolean(false),
                        Node::ArrayDecl(_)
                        | Node::Block(_)
                        | Node::Const(_)
                        | Node::FunctionDecl(_, _, _)
                        | Node::FunctionExpr(_, _, _)
                        | Node::New(_)
                        | Node::Object(_)
                        | Node::UnaryOp(_, _) => Value::boolean(true),
                        _ => panic!("SyntaxError: wrong delete argument {}", node),
                    },
                    UnaryOp::TypeOf => Value::from(v_a.get_type()),
                })
            }
            Node::BinOp(BinOp::Bit(ref op), ref a, ref b) => {
                let v_a = self.run(a)?;
                let v_b = self.run(b)?;
                Ok(match *op {
                    BitOp::And => v_a & v_b,
                    BitOp::Or => v_a | v_b,
                    BitOp::Xor => v_a ^ v_b,
                    BitOp::Shl => v_a << v_b,
                    BitOp::Shr => v_a >> v_b,
                    // TODO Fix
                    BitOp::UShr => v_a >> v_b,
                })
            }
            Node::BinOp(BinOp::Comp(ref op), ref a, ref b) => {
                let mut v_r_a = self.run(a)?;
                let mut v_r_b = self.run(b)?;
                let mut v_a = v_r_a.borrow_mut();
                let mut v_b = v_r_b.borrow_mut();
                Ok(Value::from(match *op {
                    CompOp::Equal => v_r_a.equals(v_b, self),
                    CompOp::NotEqual => !v_r_a.equals(v_b, self),
                    CompOp::StrictEqual => v_r_a.strict_equals(v_b),
                    CompOp::StrictNotEqual => !v_r_a.strict_equals(v_b),
                    CompOp::GreaterThan => v_a.to_number() > v_b.to_number(),
                    CompOp::GreaterThanOrEqual => v_a.to_number() >= v_b.to_number(),
                    CompOp::LessThan => v_a.to_number() < v_b.to_number(),
                    CompOp::LessThanOrEqual => v_a.to_number() <= v_b.to_number(),
                    CompOp::In => {
                        if !v_b.is_object() {
                            panic!("TypeError: {} is not an Object.", v_b);
                        }
                        let key = self.to_property_key(&mut v_a);
                        self.has_property(&mut v_b, &key)
                    }
                }))
            }
            Node::BinOp(BinOp::Log(ref op), ref a, ref b) => {
                // turn a `Value` into a `bool`
                let to_bool = |value| bool::from(&value);
                Ok(match *op {
                    LogOp::And => Value::from(to_bool(self.run(a)?) && to_bool(self.run(b)?)),
                    LogOp::Or => Value::from(to_bool(self.run(a)?) || to_bool(self.run(b)?)),
                })
            }
            Node::BinOp(BinOp::Assign(ref op), ref a, ref b) => match a.deref() {
                Node::Local(ref name) => {
                    let v_a = self.realm.environment.get_binding_value(&name);
                    let v_b = self.run(b)?;
                    let value = exec_assign_op(op, v_a, v_b);
                    self.realm
                        .environment
                        .set_mutable_binding(&name, value.clone(), true);
                    Ok(value)
                }
                Node::GetConstField(ref obj, ref field) => {
                    let v_r_a = self.run(obj)?;
                    let v_a = v_r_a.get_field_slice(field);
                    let v_b = self.run(b)?;
                    let value = exec_assign_op(op, v_a, v_b);
                    v_r_a
                        .borrow()
                        .set_field_slice(&field.clone(), value.clone());
                    Ok(value)
                }
                _ => Ok(Value::undefined()),
            },
            Node::New(ref call) => {
                let (callee, args) = match call.as_ref() {
                    Node::Call(callee, args) => (callee, args),
                    _ => unreachable!("Node::New(ref call): 'call' must only be Node::Call type."),
                };

                let func_object = self.run(callee)?;
                let mut v_args = Vec::with_capacity(args.len());
                for arg in args.iter() {
                    v_args.push(self.run(arg)?);
                }
                let mut this = Value::new_object(None);
                // Create a blank object, then set its __proto__ property to the [Constructor].prototype
                this.borrow().set_internal_slot(
                    INSTANCE_PROTOTYPE,
                    func_object.borrow().get_field_slice(PROTOTYPE),
                );

                match *(func_object.borrow()).deref() {
                    ValueData::Object(ref o) => (*o.deref().clone().borrow_mut())
                        .func
                        .as_ref()
                        .unwrap()
                        .construct(&mut func_object.clone(), &v_args, self, &mut this),
                    _ => Ok(Value::undefined()),
                }
            }
            Node::Return(ref ret) => {
                let result = match *ret {
                    Some(ref v) => self.run(v),
                    None => Ok(Value::undefined()),
                };
                // Set flag for return
                self.is_return = true;
                result
            }
            Node::Throw(ref ex) => Err(self.run(ex)?),
            Node::Assign(ref ref_e, ref val_e) => {
                let val = self.run(val_e)?;
                match ref_e.deref() {
                    Node::Local(ref name) => {
                        if self.realm.environment.has_binding(name) {
                            // Binding already exists
                            self.realm
                                .environment
                                .set_mutable_binding(&name, val.clone(), true);
                        } else {
                            self.realm.environment.create_mutable_binding(
                                name.clone(),
                                true,
                                VariableScope::Function,
                            );
                            self.realm.environment.initialize_binding(name, val.clone());
                        }
                    }
                    Node::GetConstField(ref obj, ref field) => {
                        let val_obj = self.run(obj)?;
                        val_obj
                            .borrow()
                            .set_field_slice(&field.clone(), val.clone());
                    }
                    Node::GetField(ref obj, ref field) => {
                        let val_obj = self.run(obj)?;
                        let val_field = self.run(field)?;
                        val_obj.borrow().set_field(val_field, val.clone());
                    }
                    _ => (),
                }
                Ok(val)
            }
            Node::VarDecl(ref vars) => {
                for var in vars.iter() {
                    let (name, value) = var.clone();
                    let val = match value {
                        Some(v) => self.run(&v)?,
                        None => Value::undefined(),
                    };
                    self.realm.environment.create_mutable_binding(
                        name.clone(),
                        false,
                        VariableScope::Function,
                    );
                    self.realm.environment.initialize_binding(&name, val);
                }
                Ok(Value::undefined())
            }
            Node::LetDecl(ref vars) => {
                for var in vars.iter() {
                    let (name, value) = var.clone();
                    let val = match value {
                        Some(v) => self.run(&v)?,
                        None => Value::undefined(),
                    };
                    self.realm.environment.create_mutable_binding(
                        name.clone(),
                        false,
                        VariableScope::Block,
                    );
                    self.realm.environment.initialize_binding(&name, val);
                }
                Ok(Value::undefined())
            }
            Node::ConstDecl(ref vars) => {
                for (name, value) in vars.iter() {
                    self.realm.environment.create_immutable_binding(
                        name.clone(),
                        false,
                        VariableScope::Block,
                    );
                    let val = self.run(&value)?;
                    self.realm.environment.initialize_binding(&name, val);
                }
                Ok(Value::undefined())
            }
            Node::StatementList(ref list) => {
                let mut obj = Value::null();
                for (i, item) in list.iter().enumerate() {
                    let val = self.run(item)?;
                    // early return
                    if self.is_return {
                        obj = val;
                        break;
                    }
                    if i + 1 == list.len() {
                        obj = val;
                    }
                }

                Ok(obj)
            }
            Node::Spread(ref node) => {
                // TODO: for now we can do nothing but return the value as-is
                self.run(node)
            }
            Node::This => {
                // Will either return `this` binding or undefined
                Ok(self.realm.environment.get_this_binding())
            }
            ref i => unimplemented!("{}", i),
        }
    }
}

impl Interpreter {
    /// Get the Interpreter's realm
    pub(crate) fn get_realm(&self) -> &Realm {
        &self.realm
    }

    /// Utility to create a function Value for Function Declarations, Arrow Functions or Function Expressions
    pub(crate) fn create_function(
        &mut self,
        args: Box<[FormalParameter]>,
        expr: &Node,
        this_mode: ThisMode,
    ) -> Value {
        let function_prototype = &self
            .realm
            .environment
            .get_global_object()
            .expect("Could not get the global object")
            .get_field_slice("Function")
            .get_field_slice("Prototype");

        // Every new function has a prototype property pre-made
        let global_val = &self
            .realm
            .environment
            .get_global_object()
            .expect("Could not get the global object");
        let proto = Value::new_object(Some(global_val));

        let func = FunctionObject::create_ordinary(
            args.clone(),
            self.realm.environment.get_current_environment().clone(),
            FunctionBody::Ordinary(expr.clone()),
            this_mode,
        );

        let mut new_func = Object::function();
        new_func.set_func(func);
        let val = Value::from(new_func);
        val.set_internal_slot(INSTANCE_PROTOTYPE, function_prototype.clone());
        val.set_field_slice(PROTOTYPE, proto);
        val.set_field_slice("length", Value::from(args.len()));

        val
    }

    /// https://tc39.es/ecma262/#sec-call
    pub(crate) fn call(
        &mut self,
        f: &Value,
        this: &mut Value,
        arguments_list: &[Value],
    ) -> ResultValue {
        // All functions should be objects, and eventually will be.
        // During this transition call will support both native functions and function objects
        match (*f).deref() {
            ValueData::Object(ref obj) => match (*obj).deref().borrow().func {
                Some(ref func) => func.call(&mut f.clone(), arguments_list, self, this),
                None => panic!("Expected function"),
            },
            _ => Err(Value::undefined()),
        }
    }

    /// https://tc39.es/ecma262/#sec-ordinarytoprimitive
    fn ordinary_to_primitive(&mut self, o: &mut Value, hint: &str) -> Value {
        debug_assert!(o.get_type() == "object");
        debug_assert!(hint == "string" || hint == "number");
        let method_names: Vec<&str> = if hint == "string" {
            vec!["toString", "valueOf"]
        } else {
            vec!["valueOf", "toString"]
        };
        for name in method_names.iter() {
            let method: Value = o.get_field_slice(name);
            if method.is_function() {
                let result = self.call(&method, o, &[]);
                match result {
                    Ok(val) => {
                        if val.is_object() {
                            // TODO: throw exception
                            continue;
                        } else {
                            return val;
                        }
                    }
                    Err(_) => continue,
                }
            }
        }

        Value::undefined()
    }

    /// The abstract operation ToPrimitive takes an input argument and an optional argument PreferredType.
    /// https://tc39.es/ecma262/#sec-toprimitive
    #[allow(clippy::wrong_self_convention)]
    pub fn to_primitive(&mut self, input: &mut Value, preferred_type: Option<&str>) -> Value {
        let mut hint: &str;
        match (*input).deref() {
            ValueData::Object(_) => {
                hint = match preferred_type {
                    None => "default",
                    Some(pt) => match pt {
                        "string" => "string",
                        "number" => "number",
                        _ => "default",
                    },
                };

                // Skip d, e we don't support Symbols yet
                // TODO: add when symbols are supported
                if hint == "default" {
                    hint = "number";
                };

                self.ordinary_to_primitive(input, hint)
            }
            _ => input.clone(),
        }
    }

    /// Converts a value into a `String`.
    ///
    /// https://tc39.es/ecma262/#sec-tostring
    #[allow(clippy::wrong_self_convention)]
    pub fn to_string(&mut self, value: &Value) -> Value {
        match *value.deref().borrow() {
            ValueData::Undefined => Value::from("undefined"),
            ValueData::Null => Value::from("null"),
            ValueData::Boolean(ref boolean) => Value::from(boolean.to_string()),
            ValueData::Rational(ref num) => Value::from(num.to_string()),
            ValueData::Integer(ref num) => Value::from(num.to_string()),
            ValueData::String(ref string) => Value::from(string.clone()),
            ValueData::BigInt(ref bigint) => Value::from(bigint.to_string()),
            ValueData::Object(_) => {
                let prim_value = self.to_primitive(&mut (value.clone()), Some("string"));
                self.to_string(&prim_value)
            }
            _ => Value::from("function(){...}"),
        }
    }

    /// The abstract operation ToPropertyKey takes argument argument. It converts argument to a value that can be used as a property key.
    /// https://tc39.es/ecma262/#sec-topropertykey
    #[allow(clippy::wrong_self_convention)]
    pub fn to_property_key(&mut self, value: &mut Value) -> Value {
        let key = self.to_primitive(value, Some("string"));
        if key.is_symbol() {
            key
        } else {
            self.to_string(&key)
        }
    }

    /// https://tc39.es/ecma262/#sec-hasproperty
    pub fn has_property(&self, obj: &mut Value, key: &Value) -> bool {
        if let Some(obj) = obj.as_object() {
            if !Property::is_property_key(key) {
                false
            } else {
                obj.has_property(key)
            }
        } else {
            false
        }
    }

    /// The abstract operation ToObject converts argument to a value of type Object
    /// https://tc39.es/ecma262/#sec-toobject
    #[allow(clippy::wrong_self_convention)]
    pub fn to_object(&mut self, value: &Value) -> ResultValue {
        match *value.deref().borrow() {
            ValueData::Undefined | ValueData::Integer(_) | ValueData::Null => {
                Err(Value::undefined())
            }
            ValueData::Boolean(_) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Boolean")
                    .get_field_slice(PROTOTYPE);

                let bool_obj = Value::new_object_from_prototype(proto, ObjectKind::Boolean);
                bool_obj.set_internal_slot("BooleanData", value.clone());
                Ok(bool_obj)
            }
            ValueData::Rational(_) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Number")
                    .get_field_slice(PROTOTYPE);
                let number_obj = Value::new_object_from_prototype(proto, ObjectKind::Number);
                number_obj.set_internal_slot("NumberData", value.clone());
                Ok(number_obj)
            }
            ValueData::String(_) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("String")
                    .get_field_slice(PROTOTYPE);
                let string_obj = Value::new_object_from_prototype(proto, ObjectKind::String);
                string_obj.set_internal_slot("StringData", value.clone());
                Ok(string_obj)
            }
            ValueData::Object(_) | ValueData::Symbol(_) => Ok(value.clone()),
            ValueData::BigInt(_) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("BigInt")
                    .get_field_slice(PROTOTYPE);
                let bigint_obj = Value::new_object_from_prototype(proto, ObjectKind::BigInt);
                bigint_obj.set_internal_slot("BigIntData", value.clone());
                Ok(bigint_obj)
            }
        }
    }

    /// value_to_rust_string() converts a value into a rust heap allocated string
    pub fn value_to_rust_string(&mut self, value: &Value) -> String {
        match *value.deref().borrow() {
            ValueData::Null => String::from("null"),
            ValueData::Boolean(ref boolean) => boolean.to_string(),
            ValueData::Rational(ref num) => num.to_string(),
            ValueData::Integer(ref num) => num.to_string(),
            ValueData::String(ref string) => string.clone(),
            ValueData::BigInt(ref bigint) => bigint.to_string(),
            ValueData::Object(_) => {
                let prim_value = self.to_primitive(&mut (value.clone()), Some("string"));
                self.to_string(&prim_value).to_string()
            }
            _ => String::from("undefined"),
        }
    }

    pub fn value_to_rust_number(&mut self, value: &Value) -> f64 {
        match *value.deref().borrow() {
            ValueData::Null => f64::from(0),
            ValueData::Boolean(boolean) => {
                if boolean {
                    f64::from(1)
                } else {
                    f64::from(0)
                }
            }
            ValueData::Rational(num) => num,
            ValueData::Integer(num) => f64::from(num),
            ValueData::String(ref string) => string.parse::<f64>().unwrap(),
            ValueData::BigInt(ref bigint) => bigint.to_f64(),
            ValueData::Object(_) => {
                let prim_value = self.to_primitive(&mut (value.clone()), Some("number"));
                self.to_string(&prim_value)
                    .to_string()
                    .parse::<f64>()
                    .expect("cannot parse valur to x64")
            }
            _ => {
                // TODO: Make undefined?
                f64::from(0)
            }
        }
    }

    /// `extract_array_properties` converts an array object into a rust vector of Values.
    /// This is useful for the spread operator, for any other object an `Err` is returned
    fn extract_array_properties(&mut self, value: &Value) -> Result<Vec<Value>, ()> {
        if let ValueData::Object(ref x) = *value.deref().borrow() {
            // Check if object is array
            if x.deref().borrow().kind == ObjectKind::Array {
                let length: i32 =
                    self.value_to_rust_number(&value.get_field_slice("length")) as i32;
                let values: Vec<Value> = (0..length)
                    .map(|idx| value.get_field_slice(&idx.to_string()))
                    .collect();
                return Ok(values);
            }

            return Err(());
        }

        Err(())
    }

    fn set_value(&mut self, node: &Node, value: Value) -> ResultValue {
        match node {
            Node::Local(ref name) => {
                self.realm
                    .environment
                    .set_mutable_binding(name, value.clone(), true);
                Ok(value)
            }
            Node::GetConstField(ref obj, ref field) => {
                Ok(self.run(obj)?.set_field_slice(field, value))
            }
            Node::GetField(ref obj, ref field) => {
                Ok(self.run(obj)?.set_field(self.run(field)?, value))
            }
            _ => panic!("TypeError: invalid assignment to {}", node),
        }
    }
}