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
//! Execution of the AST, this is where the interpreter actually runs

mod array;
mod block;
mod break_node;
mod conditional;
mod declaration;
mod exception;
mod expression;
mod field;
mod identifier;
mod iteration;
mod object;
mod operator;
mod return_smt;
mod spread;
mod statement_list;
mod switch;
#[cfg(test)]
mod tests;
mod throw;
mod try_node;

use crate::{
    builtins::{
        function::{Function as FunctionObject, FunctionBody, ThisMode},
        object::{Object, ObjectData, INSTANCE_PROTOTYPE, PROTOTYPE},
        property::Property,
        value::{RcBigInt, RcString, ResultValue, Type, Value},
        BigInt, Number,
    },
    realm::Realm,
    syntax::ast::{
        constant::Const,
        node::{FormalParameter, Node, StatementList},
    },
    BoaProfiler,
};
use std::convert::TryFrom;
use std::ops::Deref;

pub trait Executable {
    /// Runs this executable in the given executor.
    fn run(&self, interpreter: &mut Interpreter) -> ResultValue;
}

#[derive(Debug, Eq, PartialEq)]
pub(crate) enum InterpreterState {
    Executing,
    Return,
    Break(Option<String>),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PreferredType {
    String,
    Number,
    Default,
}

/// A Javascript intepreter
#[derive(Debug)]
pub struct Interpreter {
    /// the current state of the interpreter.
    state: InterpreterState,

    /// realm holds both the global object and the environment
    pub realm: Realm,

    /// This is for generating an unique internal `Symbol` hash.
    symbol_count: u32,
}

impl Interpreter {
    /// Creates a new interpreter.
    pub fn new(realm: Realm) -> Self {
        Self {
            state: InterpreterState::Executing,
            realm,
            symbol_count: 0,
        }
    }

    /// Retrieves the `Realm` of this executor.
    #[inline]
    pub(crate) fn realm(&self) -> &Realm {
        &self.realm
    }

    /// Retrieves the `Realm` of this executor as a mutable reference.
    #[inline]
    pub(crate) fn realm_mut(&mut self) -> &mut Realm {
        &mut self.realm
    }

    /// Generates a new `Symbol` internal hash.
    ///
    /// This currently is an incremented value.
    #[inline]
    pub(crate) fn generate_hash(&mut self) -> u32 {
        let hash = self.symbol_count;
        self.symbol_count += 1;
        hash
    }

    /// Utility to create a function Value for Function Declarations, Arrow Functions or Function Expressions
    pub(crate) fn create_function<P, B>(
        &mut self,
        params: P,
        body: B,
        this_mode: ThisMode,
        constructable: bool,
        callable: bool,
    ) -> Value
    where
        P: Into<Box<[FormalParameter]>>,
        B: Into<StatementList>,
    {
        let function_prototype = &self
            .realm
            .environment
            .get_global_object()
            .expect("Could not get the global object")
            .get_field("Function")
            .get_field(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 params = params.into();
        let params_len = params.len();
        let func = FunctionObject::new(
            params,
            Some(self.realm.environment.get_current_environment().clone()),
            FunctionBody::Ordinary(body.into()),
            this_mode,
            constructable,
            callable,
        );

        let new_func = Object::function(func);

        let val = Value::from(new_func);
        val.set_internal_slot(INSTANCE_PROTOTYPE, function_prototype.clone());
        val.set_field(PROTOTYPE, proto);
        val.set_field("length", Value::from(params_len));

        val
    }

    /// <https://tc39.es/ecma262/#sec-call>
    pub(crate) fn call(
        &mut self,
        f: &Value,
        this: &Value,
        arguments_list: &[Value],
    ) -> ResultValue {
        match *f {
            Value::Object(ref obj) => {
                let obj = obj.borrow();
                if let ObjectData::Function(ref func) = obj.data {
                    return func.call(f.clone(), this, arguments_list, self);
                }
                self.throw_type_error("not a function")
            }
            _ => Err(Value::undefined()),
        }
    }

    /// Converts a value into a rust heap allocated string.
    #[allow(clippy::wrong_self_convention)]
    pub fn to_string(&mut self, value: &Value) -> Result<RcString, Value> {
        match value {
            Value::Null => Ok(RcString::from("null")),
            Value::Undefined => Ok(RcString::from("undefined".to_owned())),
            Value::Boolean(boolean) => Ok(RcString::from(boolean.to_string())),
            Value::Rational(rational) => Ok(RcString::from(Number::to_native_string(*rational))),
            Value::Integer(integer) => Ok(RcString::from(integer.to_string())),
            Value::String(string) => Ok(string.clone()),
            Value::Symbol(_) => Err(self.construct_type_error("can't convert symbol to string")),
            Value::BigInt(ref bigint) => Ok(RcString::from(bigint.to_string())),
            Value::Object(_) => {
                let primitive = self.to_primitive(value, PreferredType::String)?;
                self.to_string(&primitive)
            }
        }
    }

    /// Helper function.
    #[allow(clippy::wrong_self_convention)]
    pub fn to_bigint(&mut self, value: &Value) -> Result<RcBigInt, Value> {
        match value {
            Value::Null => Err(self.construct_type_error("cannot convert null to a BigInt")),
            Value::Undefined => {
                Err(self.construct_type_error("cannot convert undefined to a BigInt"))
            }
            Value::String(ref string) => Ok(RcBigInt::from(BigInt::from_string(string, self)?)),
            Value::Boolean(true) => Ok(RcBigInt::from(BigInt::from(1))),
            Value::Boolean(false) => Ok(RcBigInt::from(BigInt::from(0))),
            Value::Integer(num) => Ok(RcBigInt::from(BigInt::from(*num))),
            Value::Rational(num) => {
                if let Ok(bigint) = BigInt::try_from(*num) {
                    return Ok(RcBigInt::from(bigint));
                }
                Err(self.construct_type_error(format!(
                    "The number {} cannot be converted to a BigInt because it is not an integer",
                    num
                )))
            }
            Value::BigInt(b) => Ok(b.clone()),
            Value::Object(_) => {
                let primitive = self.to_primitive(value, PreferredType::Number)?;
                self.to_bigint(&primitive)
            }
            Value::Symbol(_) => Err(self.construct_type_error("cannot convert Symbol to a BigInt")),
        }
    }

    /// Converts a value to a non-negative integer if it is a valid integer index value.
    ///
    /// See: https://tc39.es/ecma262/#sec-toindex
    #[allow(clippy::wrong_self_convention)]
    pub fn to_index(&mut self, value: &Value) -> Result<usize, Value> {
        if value.is_undefined() {
            return Ok(0);
        }

        let integer_index = self.to_integer(value)?;

        if integer_index < 0 {
            return Err(self.construct_range_error("Integer index must be >= 0"));
        }

        if integer_index > 2i64.pow(53) - 1 {
            return Err(self.construct_range_error("Integer index must be less than 2**(53) - 1"));
        }

        Ok(integer_index as usize)
    }

    /// Converts a value to an integral 64 bit signed integer.
    ///
    /// See: https://tc39.es/ecma262/#sec-tointeger
    #[allow(clippy::wrong_self_convention)]
    pub fn to_integer(&mut self, value: &Value) -> Result<i64, Value> {
        let number = self.to_number(value)?;

        if number.is_nan() {
            return Ok(0);
        }

        Ok(number as i64)
    }

    /// Converts a value to a double precision floating point.
    ///
    /// See: https://tc39.es/ecma262/#sec-tonumber
    #[allow(clippy::wrong_self_convention)]
    pub fn to_number(&mut self, value: &Value) -> Result<f64, Value> {
        match *value {
            Value::Null => Ok(0.0),
            Value::Undefined => Ok(f64::NAN),
            Value::Boolean(b) => Ok(if b { 1.0 } else { 0.0 }),
            // TODO: this is probably not 100% correct, see https://tc39.es/ecma262/#sec-tonumber-applied-to-the-string-type
            Value::String(ref string) => Ok(string.parse().unwrap_or(f64::NAN)),
            Value::Rational(number) => Ok(number),
            Value::Integer(integer) => Ok(f64::from(integer)),
            Value::Symbol(_) => Err(self.construct_type_error("argument must not be a symbol")),
            Value::BigInt(_) => Err(self.construct_type_error("argument must not be a bigint")),
            Value::Object(_) => {
                let primitive = self.to_primitive(value, PreferredType::Number)?;
                self.to_number(&primitive)
            }
        }
    }

    /// It returns value converted to a numeric value of type Number or BigInt.
    ///
    /// See: https://tc39.es/ecma262/#sec-tonumeric
    #[allow(clippy::wrong_self_convention)]
    pub fn to_numeric(&mut self, value: &Value) -> ResultValue {
        let primitive = self.to_primitive(value, PreferredType::Number)?;
        if primitive.is_bigint() {
            return Ok(primitive);
        }
        Ok(Value::from(self.to_number(&primitive)?))
    }

    /// This is a more specialized version of `to_numeric`.
    ///
    /// It returns value converted to a numeric value of type `Number`.
    ///
    /// See: https://tc39.es/ecma262/#sec-tonumeric
    #[allow(clippy::wrong_self_convention)]
    pub(crate) fn to_numeric_number(&mut self, value: &Value) -> Result<f64, Value> {
        let primitive = self.to_primitive(value, PreferredType::Number)?;
        if let Some(ref bigint) = primitive.as_bigint() {
            return Ok(bigint.to_f64());
        }
        Ok(self.to_number(&primitive)?)
    }

    /// 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
    pub(crate) fn extract_array_properties(&mut self, value: &Value) -> Result<Vec<Value>, ()> {
        if let Value::Object(ref x) = value {
            // Check if object is array
            if let ObjectData::Array = x.deref().borrow().data {
                let length = i32::from(&value.get_field("length"));
                let values = (0..length)
                    .map(|idx| value.get_field(idx.to_string()))
                    .collect();
                return Ok(values);
            }

            return Err(());
        }

        Err(())
    }

    /// Converts an object to a primitive.
    ///
    /// More information:
    ///  - [ECMAScript][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-ordinarytoprimitive
    pub(crate) fn ordinary_to_primitive(&mut self, o: &Value, hint: PreferredType) -> ResultValue {
        // 1. Assert: Type(O) is Object.
        debug_assert!(o.get_type() == Type::Object);
        // 2. Assert: Type(hint) is String and its value is either "string" or "number".
        debug_assert!(hint == PreferredType::String || hint == PreferredType::Number);

        // 3. If hint is "string", then
        //    a. Let methodNames be « "toString", "valueOf" ».
        // 4. Else,
        //    a. Let methodNames be « "valueOf", "toString" ».
        let method_names = if hint == PreferredType::String {
            ["toString", "valueOf"]
        } else {
            ["valueOf", "toString"]
        };

        // 5. For each name in methodNames in List order, do
        for name in &method_names {
            // a. Let method be ? Get(O, name).
            let method: Value = o.get_field(*name);
            // b. If IsCallable(method) is true, then
            if method.is_function() {
                // i. Let result be ? Call(method, O).
                let result = self.call(&method, &o, &[])?;
                // ii. If Type(result) is not Object, return result.
                if !result.is_object() {
                    return Ok(result);
                }
            }
        }

        // 6. Throw a TypeError exception.
        self.throw_type_error("cannot convert object to primitive value")
    }

    /// 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(crate) fn to_primitive(
        &mut self,
        input: &Value,
        preferred_type: PreferredType,
    ) -> ResultValue {
        // 1. Assert: input is an ECMAScript language value. (always a value not need to check)
        // 2. If Type(input) is Object, then
        if let Value::Object(_) = input {
            let mut hint = preferred_type;

            // Skip d, e we don't support Symbols yet
            // TODO: add when symbols are supported
            // TODO: Add other steps.
            if hint == PreferredType::Default {
                hint = PreferredType::Number;
            };

            // g. Return ? OrdinaryToPrimitive(input, hint).
            self.ordinary_to_primitive(input, hint)
        } else {
            // 3. Return input.
            Ok(input.clone())
        }
    }

    /// 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(crate) fn to_property_key(&mut self, value: &Value) -> ResultValue {
        let key = self.to_primitive(value, PreferredType::String)?;
        if key.is_symbol() {
            Ok(key)
        } else {
            self.to_string(&key).map(Value::from)
        }
    }

    /// https://tc39.es/ecma262/#sec-hasproperty
    pub(crate) fn has_property(&self, obj: &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(crate) fn to_object(&mut self, value: &Value) -> ResultValue {
        match value {
            Value::Undefined | Value::Null => {
                self.throw_type_error("cannot convert 'null' or 'undefined' to object")
            }
            Value::Boolean(boolean) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Boolean")
                    .expect("Boolean was not initialized")
                    .get_field(PROTOTYPE);

                Ok(Value::new_object_from_prototype(
                    proto,
                    ObjectData::Boolean(*boolean),
                ))
            }
            Value::Integer(integer) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Number")
                    .expect("Number was not initialized")
                    .get_field(PROTOTYPE);
                Ok(Value::new_object_from_prototype(
                    proto,
                    ObjectData::Number(f64::from(*integer)),
                ))
            }
            Value::Rational(rational) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Number")
                    .expect("Number was not initialized")
                    .get_field(PROTOTYPE);

                Ok(Value::new_object_from_prototype(
                    proto,
                    ObjectData::Number(*rational),
                ))
            }
            Value::String(ref string) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("String")
                    .expect("String was not initialized")
                    .get_field(PROTOTYPE);

                Ok(Value::new_object_from_prototype(
                    proto,
                    ObjectData::String(string.clone()),
                ))
            }
            Value::Symbol(ref symbol) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("Symbol")
                    .expect("Symbol was not initialized")
                    .get_field(PROTOTYPE);

                Ok(Value::new_object_from_prototype(
                    proto,
                    ObjectData::Symbol(symbol.clone()),
                ))
            }
            Value::BigInt(ref bigint) => {
                let proto = self
                    .realm
                    .environment
                    .get_binding_value("BigInt")
                    .expect("BigInt was not initialized")
                    .get_field(PROTOTYPE);
                let bigint_obj =
                    Value::new_object_from_prototype(proto, ObjectData::BigInt(bigint.clone()));
                Ok(bigint_obj)
            }
            Value::Object(_) => Ok(value.clone()),
        }
    }

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

    #[inline]
    pub(crate) fn set_current_state(&mut self, new_state: InterpreterState) {
        self.state = new_state
    }

    #[inline]
    pub(crate) fn get_current_state(&self) -> &InterpreterState {
        &self.state
    }

    /// Check if the `Value` can be converted to an `Object`
    ///
    /// The abstract operation `RequireObjectCoercible` takes argument argument.
    /// It throws an error if argument is a value that cannot be converted to an Object using `ToObject`.
    /// It is defined by [Table 15][table]
    ///
    /// More information:
    ///  - [ECMAScript reference][spec]
    ///
    /// [table]: https://tc39.es/ecma262/#table-14
    /// [spec]: https://tc39.es/ecma262/#sec-requireobjectcoercible
    #[inline]
    pub fn require_object_coercible<'a>(&mut self, value: &'a Value) -> Result<&'a Value, Value> {
        if value.is_null_or_undefined() {
            Err(self.construct_type_error("cannot convert null or undefined to Object"))
        } else {
            Ok(value)
        }
    }
}

impl Executable for Node {
    fn run(&self, interpreter: &mut Interpreter) -> ResultValue {
        let _timer = BoaProfiler::global().start_event("Executable", "exec");
        match *self {
            Node::Const(Const::Null) => Ok(Value::null()),
            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 block) => block.run(interpreter),
            Node::Identifier(ref identifier) => identifier.run(interpreter),
            Node::GetConstField(ref get_const_field_node) => get_const_field_node.run(interpreter),
            Node::GetField(ref get_field) => get_field.run(interpreter),
            Node::Call(ref expr) => expr.run(interpreter),
            Node::WhileLoop(ref while_loop) => while_loop.run(interpreter),
            Node::DoWhileLoop(ref do_while) => do_while.run(interpreter),
            Node::ForLoop(ref for_loop) => for_loop.run(interpreter),
            Node::If(ref if_smt) => if_smt.run(interpreter),
            Node::Switch(ref switch) => switch.run(interpreter),
            Node::Object(ref obj) => obj.run(interpreter),
            Node::ArrayDecl(ref arr) => arr.run(interpreter),
            // <https://tc39.es/ecma262/#sec-createdynamicfunction>
            Node::FunctionDecl(ref decl) => decl.run(interpreter),
            // <https://tc39.es/ecma262/#sec-createdynamicfunction>
            Node::FunctionExpr(ref expr) => expr.run(interpreter),
            Node::ArrowFunctionDecl(ref decl) => decl.run(interpreter),
            Node::BinOp(ref op) => op.run(interpreter),
            Node::UnaryOp(ref op) => op.run(interpreter),
            Node::New(ref call) => call.run(interpreter),
            Node::Return(ref ret) => ret.run(interpreter),
            Node::Throw(ref throw) => throw.run(interpreter),
            Node::Assign(ref op) => op.run(interpreter),
            Node::VarDeclList(ref decl) => decl.run(interpreter),
            Node::LetDeclList(ref decl) => decl.run(interpreter),
            Node::ConstDeclList(ref decl) => decl.run(interpreter),
            Node::Spread(ref spread) => spread.run(interpreter),
            Node::This => {
                // Will either return `this` binding or undefined
                Ok(interpreter.realm().environment.get_this_binding())
            }
            Node::Try(ref try_node) => try_node.run(interpreter),
            Node::Break(ref break_node) => break_node.run(interpreter),
            ref i => unimplemented!("{:?}", i),
        }
    }
}