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
//! A tree-walking interpreter for anything [`Interpretable`] on a [`Heap`]

use crate::prelude::*;

use crate::ast::*; // yes, EVERYTHING
use crate::builtin;
use crate::{
    function::Closure,
    object::Access,
    CallContext,
    Exception,
    Heap,
    Interpreted,
    JSObject,
    JSResult,
    JSValue,
};

// ==============================================
/// Describes things (i.e. AST nodes, [`Function`]) that can be interpreted on a [`Heap`]
pub trait Interpretable {
    /// A wrapper for `.interpret` that also resolves the result to JSValue
    fn evaluate(&self, heap: &mut Heap) -> JSResult<JSValue> {
        self.interpret(heap)?.to_value(heap)
    }

    /// Interpret `self` on the `heap`, potentially to a settable [`Interpreted::Member`].
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted>;
}

// ==============================================

impl Interpretable for Program {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        for b in self.globals_iter() {
            heap.declare_binding(b)?;
        }

        self.body.interpret(heap)
    }
}

// ==============================================

impl Interpretable for Statement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        heap.loc = self.loc.clone();
        match &self.stmt {
            Stmt::Empty => Ok(Interpreted::VOID),
            Stmt::Expr(stmt) => stmt.interpret(heap),
            Stmt::Block(stmt) => stmt.interpret(heap),
            Stmt::If(stmt) => stmt.interpret(heap),
            Stmt::Switch(stmt) => stmt.interpret(heap),
            Stmt::For(stmt) => stmt.interpret(heap),
            Stmt::ForIn(stmt) => stmt.interpret(heap),
            Stmt::DoWhile(stmt) => stmt.interpret(heap),
            Stmt::Break(stmt) => stmt.interpret(heap),
            Stmt::Continue(stmt) => stmt.interpret(heap),
            Stmt::Label(stmt) => stmt.interpret(heap),
            Stmt::Return(stmt) => stmt.interpret(heap),
            Stmt::Throw(stmt) => stmt.interpret(heap),
            Stmt::Try(stmt) => stmt.interpret(heap),
            Stmt::Variable(stmt) => stmt.interpret(heap),
            Stmt::Function(stmt) => stmt.interpret(heap),
        }
    }
}

// ==============================================

impl Interpretable for BlockStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let this_ref = heap.interpret_this();
        let outer_scope = heap.local_scope().unwrap_or(Heap::GLOBAL);
        heap.enter_new_scope(this_ref, outer_scope, |heap| {
            heap.declare(self.bindings_iter())?;

            let mut result = Interpreted::VOID;
            for stmt in self.body.iter() {
                result = stmt.interpret(heap)?;
            }
            Ok(result)
        })
    }
}

impl Interpretable for IfStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let cond = self.test.evaluate(heap)?;
        if cond.boolify(heap) {
            self.consequent.interpret(heap)
        } else if let Some(else_stmt) = self.alternate.as_ref() {
            else_stmt.interpret(heap)
        } else {
            Ok(Interpreted::VOID)
        }
    }
}

impl Interpretable for SwitchStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let switchval = self.discriminant.evaluate(heap)?;

        let mut default: Option<usize> = None; // the index of the default case, if any
        let mut found_case: Option<usize> = None;

        // search
        for (i, case) in self.cases.iter().enumerate() {
            let caseval = match &case.test {
                None => {
                    default = Some(i);
                    continue;
                }
                Some(test) => test.evaluate(heap)?,
            };

            if JSValue::strict_eq(&switchval, &caseval, heap) {
                found_case = Some(i);
                break;
            }
        }

        let end = self.cases.len();
        let restart_index = found_case.or(default).unwrap_or(end);

        // execute
        for i in restart_index..end {
            for stmt in self.cases[i].consequent.iter() {
                match stmt.interpret(heap) {
                    Ok(_) => (),
                    Err(Exception::JumpBreak(None)) => {
                        return Ok(Interpreted::VOID);
                    }
                    Err(e) => return Err(e),
                }
            }
        }
        Ok(Interpreted::VOID)
    }
}

impl ForStatement {
    fn do_init(&self, heap: &mut Heap) -> JSResult<()> {
        match self.init.as_ref() {
            None => (),
            Some(ForTarget::Expr(expr)) => {
                heap.evaluate(&expr.expression)?;
            }
            Some(ForTarget::Var(vardecl)) => {
                heap.evaluate(vardecl)?;
            }
        }
        Ok(())
    }
    /// `do_loop()` executes the loop except its `init` statement.
    /// `init` must be interpreted before this, if needed.
    fn do_loop(&self, heap: &mut Heap) -> Result<(), Exception> {
        while self.should_iterate(heap)? {
            // body
            let result = self.body.interpret(heap);
            match result {
                Ok(_) => (),
                Err(Exception::JumpContinue(None)) => (),
                Err(Exception::JumpBreak(None)) => break,
                Err(e) => return Err(e),
            };

            self.do_update(heap)?;
        }
        Ok(())
    }

    fn should_iterate(&self, heap: &mut Heap) -> JSResult<bool> {
        match self.test.as_ref() {
            None => Ok(true),
            Some(testexpr) => {
                let result = testexpr.evaluate(heap)?;
                Ok(result.boolify(heap))
            }
        }
    }

    fn do_update(&self, heap: &mut Heap) -> Result<(), Exception> {
        if let Some(updateexpr) = self.update.as_ref() {
            updateexpr.interpret(heap)?;
        }
        Ok(())
    }

    fn needs_variable(&self) -> Option<Identifier> {
        use DeclarationKind::*;
        if let Some(ForTarget::Var(vardecl)) = self.init.as_ref() {
            if vardecl.kind == Let || vardecl.kind == Const {
                let (name, _) = &vardecl.declarations[0];
                return Some(name.clone());
            }
        }
        None
    }
}

impl Interpretable for ForStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        if let Some(var) = self.needs_variable() {
            let this_ref = heap.interpret_this();
            let outer_scope = heap.local_scope().unwrap_or(Heap::GLOBAL);
            heap.enter_new_scope(this_ref, outer_scope, |heap| {
                heap.declare_variable(&var)?;
                self.do_init(heap)?;
                self.do_loop(heap)
            })?;
        } else {
            self.do_init(heap)?;
            self.do_loop(heap)?;
        }
        Ok(Interpreted::VOID)
    }
}

impl ForInStatement {}

impl Interpretable for ForInStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let iteratee = self.right.evaluate(heap)?.objectify(heap);

        let assignexpr = match &self.left {
            ForTarget::Expr(exprstmt) => exprstmt.expression.clone(),
            ForTarget::Var(vardecl) => {
                let (ident, _) = &vardecl.declarations[0];
                Expression::from(ident.clone())
            }
        };

        let mut visited = HashSet::new();
        let mut objref = iteratee;
        while objref != Heap::NULL {
            for name in heap.get(objref).get_own_keys() {
                if !visited.insert(name.clone()) {
                    continue;
                }
                match heap.get(objref).get_own_property(name.as_str()) {
                    Some(prop) if prop.is_enumerable() => prop,
                    Some(_) => continue, // not enumerable
                    None => continue,    // whoops, it disappeared
                };

                assignexpr
                    .interpret(heap)?
                    .put_value(JSValue::from(name), heap)
                    .or_else(crate::error::ignore_set_readonly)?;

                match self.body.interpret(heap) {
                    Ok(_) => (),
                    Err(Exception::JumpContinue(None)) => continue,
                    Err(Exception::JumpBreak(None)) => {
                        return Ok(Interpreted::VOID);
                    }
                    Err(e) => {
                        return Err(e);
                    }
                }
            }

            objref = heap.get(objref).get_proto();
        }
        Ok(Interpreted::VOID)
    }
}

impl Interpretable for DoWhileStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        Ok(Interpreted::from(loop {
            let result = heap.evaluate(self.body.as_ref())?;
            if let Some(test) = self.test.as_ref() {
                let condval = heap.evaluate(test)?;
                if !condval.boolify(heap) {
                    break result;
                }
            }
        }))
    }
}

impl Interpretable for BreakStatement {
    fn interpret(&self, _heap: &mut Heap) -> JSResult<Interpreted> {
        let BreakStatement(maybe_label) = self;
        Err(Exception::JumpBreak(maybe_label.clone()))
    }
}

impl Interpretable for ContinueStatement {
    fn interpret(&self, _heap: &mut Heap) -> JSResult<Interpreted> {
        let ContinueStatement(maybe_label) = self;
        Err(Exception::JumpContinue(maybe_label.clone()))
    }
}

impl LabelStatement {
    fn continue_loop(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let LabelStatement(label, body) = self;
        loop {
            // must be a loop to continue
            let loop_stmt = match &body.stmt {
                Stmt::For(stmt) => stmt,
                Stmt::ForIn(_) => todo!("continue from ForInStatement"),
                _ => return Err(Exception::SyntaxErrorContinueLabelNotALoop(label.clone())),
            };

            loop_stmt.do_update(heap)?;
            let result = loop_stmt.do_loop(heap);
            match result {
                Err(Exception::JumpContinue(Some(target))) if &target == label => continue,
                Err(Exception::JumpBreak(Some(target))) if &target == label => break,
                Err(e) => return Err(e),
                Ok(()) => break,
            }
        }
        Ok(Interpreted::VOID)
    }
}

impl Interpretable for LabelStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let LabelStatement(label, body) = self;

        let result = body.interpret(heap);
        match result {
            Err(Exception::JumpBreak(Some(target))) if &target == label => Ok(Interpreted::VOID),
            Err(Exception::JumpContinue(Some(target))) if &target == label => {
                self.continue_loop(heap)
            }
            _ => result,
        }
    }
}

impl Interpretable for ExpressionStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let value = self.expression.evaluate(heap)?;
        Ok(Interpreted::Value(value))
    }
}

impl Interpretable for ReturnStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let ReturnStatement(argument) = self;
        let returned = match argument {
            None => Interpreted::VOID,
            Some(argexpr) => argexpr.interpret(heap)?,
        };
        Err(Exception::JumpReturn(returned))
    }
}

impl Interpretable for ThrowStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let ThrowStatement(exc_expr) = self;
        let exc_value = exc_expr.evaluate(heap)?;
        heap.throw(Exception::UserThrown(exc_value))
    }
}

impl CatchClause {
    fn interpret(&self, exc: &Exception, heap: &mut Heap) -> JSResult<Interpreted> {
        let this_ref = heap.interpret_this();
        let scope_ref = heap.local_scope().unwrap_or(Heap::GLOBAL);

        heap.enter_new_scope(this_ref, scope_ref, |heap| {
            let error_value: JSValue = match exc {
                Exception::UserThrown(errval) => errval.clone(),
                Exception::JumpBreak(_) | Exception::JumpContinue(_) | Exception::JumpReturn(_) => {
                    panic!("Impossible to catch: {:?}", exc)
                }
                //Exception::ReferenceNotFound(ident) => { // TODO: ReferenceError
                _ => {
                    let message = format!("{:?}", exc);
                    let args = vec![Interpreted::from(message)];
                    let errval = builtin::error::error_constructor(
                        CallContext::from(args)
                            .with_this(this_ref)
                            .with_name("Error".into()),
                        heap,
                    )?;
                    errval.to_value(heap)?
                }
            };

            heap.scope_mut()
                .set_nonconf(self.param.0.clone(), error_value)?;
            self.body.interpret(heap)
        })
    }
}

impl TryStatement {
    fn run_finalizer(&self, heap: &mut Heap) -> Result<(), Exception> {
        if let Some(finalizer) = self.finalizer.as_ref() {
            finalizer.interpret(heap)?;
        }
        Ok(())
    }
}

impl Interpretable for TryStatement {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let result = self.block.interpret(heap);
        match &result {
            Ok(_)
            | Err(Exception::JumpReturn(_))
            | Err(Exception::JumpBreak(_))
            | Err(Exception::JumpContinue(_)) => {
                self.run_finalizer(heap)?;
                result
            }
            Err(exc) => {
                let result = match &self.handler {
                    None => result,
                    Some(catch) => catch.interpret(exc, heap),
                };
                self.run_finalizer(heap)?;
                result
            }
        }
    }
}

impl Interpretable for VariableDeclaration {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        for (name, maybe_init) in &self.declarations {
            if let Some(initexpr) = maybe_init.as_ref() {
                let value = initexpr.evaluate(heap)?;
                match heap.lookup_var(name.as_str()) {
                    Some(Interpreted::Member { of, name }) => {
                        heap.get_mut(of)
                            .set_property(name, value)
                            .or_else(crate::error::ignore_set_readonly)?;
                    }
                    _ => return Err(Exception::ReferenceNotFound(name.clone())),
                }
            }
        }
        Ok(Interpreted::VOID)
    }
}

impl Interpretable for FunctionDeclaration {
    fn interpret(&self, _heap: &mut Heap) -> JSResult<Interpreted> {
        // no-op: the work in done in Closure::call()
        Ok(Interpreted::VOID)
    }
}

impl Interpretable for Expression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        heap.loc = self.loc.clone();
        match &self.expr {
            Expr::Literal(expr) => expr.interpret(heap),
            Expr::Identifier(expr) => expr.interpret(heap),
            Expr::BinaryOp(expr) => expr.interpret(heap),
            Expr::LogicalOp(expr) => expr.interpret(heap),
            Expr::Call(expr) => expr.interpret(heap),
            Expr::Array(expr) => expr.interpret(heap),
            Expr::Member(expr) => expr.interpret(heap),
            Expr::Object(expr) => expr.interpret(heap),
            Expr::Assign(expr) => expr.interpret(heap),
            Expr::Conditional(expr) => expr.interpret(heap),
            Expr::Unary(expr) => expr.interpret(heap),
            Expr::Update(expr) => expr.interpret(heap),
            Expr::Sequence(expr) => expr.interpret(heap),
            Expr::Function(expr) => expr.interpret(heap),
            Expr::New(expr) => expr.interpret(heap),
            Expr::This => Ok(Interpreted::from(heap.interpret_this())),
        }
    }
}

impl Interpretable for Literal {
    fn interpret(&self, _heap: &mut Heap) -> JSResult<Interpreted> {
        let value = self.to_value();
        Ok(Interpreted::Value(value))
    }
}

impl Interpretable for Identifier {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let name = &self.0;
        let place = heap
            .lookup_var(name)
            .unwrap_or_else(|| Interpreted::member(Heap::GLOBAL, name));
        Ok(place)
    }
}

impl Interpretable for ConditionalExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let cond = self.condexpr.evaluate(heap)?;
        if cond.boolify(heap) {
            self.thenexpr.interpret(heap)
        } else {
            self.elseexpr.interpret(heap)
        }
    }
}

impl Interpretable for LogicalExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let LogicalExpression(lexpr, op, rexpr) = self;
        let lval = lexpr.evaluate(heap)?;
        let value = match (lval.boolify(heap), op) {
            (true, BoolOp::And) | (false, BoolOp::Or) => rexpr.evaluate(heap)?,
            _ => lval,
        };
        Ok(Interpreted::Value(value))
    }
}

impl BinOp {
    fn compute(&self, lval: &JSValue, rval: &JSValue, heap: &mut Heap) -> JSResult<JSValue> {
        Ok(match self {
            BinOp::EqEq => JSValue::from(JSValue::loose_eq(lval, rval, heap)),
            BinOp::NotEq => JSValue::from(!JSValue::loose_eq(lval, rval, heap)),
            BinOp::EqEqEq => JSValue::from(JSValue::strict_eq(lval, rval, heap)),
            BinOp::NotEqEq => JSValue::from(!JSValue::strict_eq(lval, rval, heap)),
            BinOp::Less => JSValue::compare(lval, rval, heap, |a, b| a < b, |a, b| a < b),
            BinOp::Greater => JSValue::compare(lval, rval, heap, |a, b| a > b, |a, b| a > b),
            BinOp::LtEq => JSValue::compare(lval, rval, heap, |a, b| a <= b, |a, b| a <= b),
            BinOp::GtEq => JSValue::compare(lval, rval, heap, |a, b| a >= b, |a, b| a >= b),
            BinOp::Plus => JSValue::plus(lval, rval, heap)?,
            BinOp::Minus => JSValue::minus(lval, rval, heap)?,
            BinOp::Star => JSValue::numerically(lval, rval, heap, |a, b| a * b),
            BinOp::Slash => JSValue::numerically(lval, rval, heap, |a, b| a / b),
            BinOp::Percent => JSValue::numerically(lval, rval, heap, |a, b| a % b),
            BinOp::Pipe => {
                let bitor = |a, b| (a as i32 | b as i32) as f64;
                JSValue::numerically(lval, rval, heap, bitor)
            }
            BinOp::Hat => {
                let bitxor = |a, b| (a as i32 ^ b as i32) as f64;
                JSValue::numerically(lval, rval, heap, bitxor)
            }
            BinOp::Ampersand => {
                let bitand = |a, b| (a as i32 & b as i32) as f64;
                JSValue::numerically(lval, rval, heap, bitand)
            }
            BinOp::LtLt => {
                let bitshl = |a, b| ((a as i32) << ((b as u32) & 0x1f) as i32) as f64;
                JSValue::numerically(lval, rval, heap, bitshl)
            }
            BinOp::GtGt => {
                let bitshr = |a, b| ((a as i32) >> ((b as u32) & 0x1f) as i32) as f64;
                JSValue::numerically(lval, rval, heap, bitshr)
            }
            BinOp::GtGtGt => {
                let bitshru = |a, b| ((a as u32) >> (b as u32) & 0x1f) as f64;
                JSValue::numerically(lval, rval, heap, bitshru)
            }
            BinOp::In => {
                let prop = lval.stringify(heap)?;
                let objref = rval.to_ref()?;
                let object = heap.get(objref);
                let found = object.lookup_value(&prop, heap).is_some();
                JSValue::from(found)
            }
            BinOp::InstanceOf => {
                let constructor = rval.to_ref()?;
                let found = match lval.to_ref() {
                    Err(_) => false,
                    Ok(objref) => objref.isinstance(constructor, heap)?,
                };
                JSValue::from(found)
            }
        })
    }
}

impl Interpretable for BinaryExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let BinaryExpression(lexpr, op, rexpr) = self;
        let lval = lexpr.evaluate(heap)?;
        let rval = rexpr.evaluate(heap)?;
        let result = op.compute(&lval, &rval, heap)?;
        Ok(Interpreted::Value(result))
    }
}

impl Interpretable for UnaryExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let UnaryExpression(op, argexpr) = self;
        let arg = argexpr.interpret(heap)?;
        let argvalue = || arg.to_value(heap);
        let argnum = || argvalue().map(|val| val.numberify(heap).unwrap_or(f64::NAN));
        let value = match op {
            UnOp::Exclamation => JSValue::Bool(!argvalue()?.boolify(heap)),
            UnOp::Minus => JSValue::Number(-argnum()?),
            UnOp::Plus => JSValue::Number(argnum()?),
            UnOp::Tilde => {
                let num = argnum()?;
                let num = if f64::is_nan(num) { 0.0 } else { num };
                JSValue::from(-(1.0 + num))
            }
            UnOp::Void => JSValue::Undefined,
            UnOp::Typeof => JSValue::from(
                argvalue()
                    .map(|val| val.type_of(heap))
                    .unwrap_or("undefined"),
            ),
            UnOp::Delete => JSValue::from(arg.delete(heap).is_ok()),
        };
        Ok(Interpreted::Value(value))
    }
}

impl Interpretable for UpdateExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let UpdateExpression(op, prefix, argexpr) = self;
        let assignee = argexpr.interpret(heap)?;

        let oldvalue = assignee.to_value(heap)?;
        let oldnum = oldvalue.numberify(heap).unwrap_or(f64::NAN);
        let newnum = match op {
            UpdOp::Increment => oldnum + 1.0,
            UpdOp::Decrement => oldnum - 1.0,
        };

        assignee
            .put_value(JSValue::from(newnum), heap)
            .or_else(crate::error::ignore_set_readonly)?;

        let resnum = if *prefix { newnum } else { oldnum };
        Ok(Interpreted::from(resnum))
    }
}

impl Interpretable for SequenceExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let SequenceExpression(exprs) = self;

        let mut value = JSValue::Undefined;
        for expr in exprs.iter() {
            value = expr.interpret(heap)?.to_value(heap)?;
        }
        Ok(Interpreted::from(value))
    }
}

impl Interpretable for MemberExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let MemberExpression(objexpr, propexpr, computed) = self;

        // compute the name of the property:
        let propname = if *computed {
            let propval = propexpr.interpret(heap)?.to_value(heap)?;
            propval.stringify(heap)?
        } else {
            match &propexpr.expr {
                Expr::Identifier(name) => name.0.clone(),
                _ => panic!("Member(computed=false) property is not an identifier"),
            }
        };

        // get the object reference for member computation:
        let objresult = objexpr.interpret(heap)?;
        let objref = match objresult.to_value(heap)? {
            JSValue::Undefined => return Err(Exception::ReferenceNotAnObject(objresult)),
            value => value.objectify(heap),
        };

        // TODO: __proto__ as (getPrototypeOf, setPrototypeOf) property
        if propname.as_str() == "__proto__" {
            let proto = heap.get(objref).get_proto();
            return Ok(Interpreted::from(proto));
        }

        Ok(Interpreted::Member {
            of: objref,
            name: propname,
        })
    }
}

impl Interpretable for ObjectExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let mut object = JSObject::new();

        for (key, valexpr) in self.0.iter() {
            let keyname = match key {
                ObjectKey::Identifier(ident) => ident.clone(),
                ObjectKey::Computed(expr) => {
                    let result = expr.interpret(heap)?.to_value(heap)?;
                    result.stringify(heap)?
                }
            };
            let valresult = valexpr.interpret(heap)?;
            let value = valresult.to_value(heap)?;
            object.set_property(keyname, value)?;
        }

        let object_ref = heap.alloc(object);
        Ok(Interpreted::from(object_ref))
    }
}

impl Interpretable for ArrayExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let ArrayExpression(exprs) = self;
        let storage = (exprs.iter())
            .map(|expr| expr.interpret(heap)?.to_value(heap))
            .collect::<Result<Vec<JSValue>, Exception>>()?;

        let object = JSObject::from_array(storage);
        let object_ref = heap.alloc(object);
        Ok(Interpreted::from(object_ref))
    }
}

impl Interpretable for AssignmentExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let AssignmentExpression(leftexpr, modop, valexpr) = self;

        let value = valexpr.evaluate(heap)?;

        // This can be:
        // - Interpreted::Member{ existing object, attribute }
        // - Interpreted::Member{ scope, existing variable }
        // - Interpreted::Member{ global, non-existing variable }
        // - Interpreted::Value
        let assignee = leftexpr.interpret(heap)?;

        let newvalue = match modop {
            None => value,
            Some(op) => {
                let oldvalue = assignee.to_value(heap)?;
                op.compute(&oldvalue, &value, heap)?
            }
        };
        assignee
            .put_value(newvalue.clone(), heap)
            .or_else(crate::error::ignore_set_readonly)?;
        Ok(Interpreted::Value(newvalue))
    }
}

impl Interpretable for CallExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let CallExpression(callee_expr, argument_exprs) = self;

        let arguments = (argument_exprs.iter())
            .map(|argexpr| argexpr.interpret(heap))
            .collect::<Result<Vec<Interpreted>, Exception>>()?;

        let callee = callee_expr.interpret(heap)?;
        let (func_ref, this_ref, name) = callee.resolve_call(heap)?;

        heap.execute(
            func_ref,
            CallContext::from(arguments)
                .with_this(this_ref)
                .with_name(name),
        )
    }
}

impl Interpretable for NewExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let NewExpression(callee_expr, argument_exprs) = self;

        let arguments = (argument_exprs.iter())
            .map(|expr| expr.interpret(heap))
            .collect::<Result<Vec<Interpreted>, Exception>>()?;

        let callee = callee_expr.interpret(heap)?;
        let funcref = callee.to_ref(heap)?;
        let prototype_ref = (heap.get_mut(funcref))
            .get_own_value("prototype")
            .ok_or_else(|| Exception::TypeErrorGetProperty(callee, "prototype".into()))?
            .to_ref()?;

        // allocate the object
        let mut object = JSObject::new();
        object.set_proto(prototype_ref);

        let object_ref = heap.alloc(object);

        // call its constructor
        let result = heap.execute(
            funcref,
            CallContext::from(arguments)
                .with_this(object_ref)
                .with_name("<constructor>".into()),
        )?;
        match result {
            Interpreted::Value(JSValue::Ref(r)) if r != Heap::NULL => Ok(result),
            _ => Ok(Interpreted::from(object_ref)),
        }
    }
}

impl Interpretable for FunctionExpression {
    fn interpret(&self, heap: &mut Heap) -> JSResult<Interpreted> {
        let closure = Closure {
            function: Rc::clone(&self.func),
            captured_scope: heap.local_scope().unwrap_or(Heap::GLOBAL),
        };

        let function_object = JSObject::from_closure(closure);
        let function_ref = heap.alloc(function_object);

        let prototype_ref = heap.alloc(JSObject::new());
        heap.get_mut(function_ref)
            .define_own_property("prototype".into(), Access::WRITE)?;
        heap.get_mut(function_ref)
            .set_property("prototype".into(), prototype_ref)?;
        heap.get_mut(prototype_ref)
            .set_hidden("constructor".into(), function_ref)?;

        Ok(Interpreted::from(function_ref))
    }
}