nova_vm 1.0.0

Nova Virtual Machine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Heap constants for initializing the heap
//!
//! These define the order in which built-in prototypes and constructors
//! are placed into the heap vectors. The order is based on the [ECMAScript
//! specification](https://tc39.es/ecma262/).

use std::num::NonZeroU32;

use crate::{
    ecmascript::{ObjectShape, PropertyKey, ProtoIntrinsics, Symbol, Value},
    heap::HeapIndexHandle,
};

#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum IntrinsicObjectIndexes {
    // +==================================================================+
    // | First the list of built-in prototypes and non-prototypal objects |
    // +==================================================================+

    // Fundamental objects
    ObjectPrototype,
    SymbolPrototype,
    ErrorPrototype,

    // Numbers and dates
    BigIntPrototype,
    #[cfg(feature = "math")]
    MathObject,
    #[cfg(feature = "date")]
    DatePrototype,
    #[cfg(feature = "temporal")]
    Temporal,
    #[cfg(feature = "temporal")]
    TemporalInstantPrototype,
    #[cfg(feature = "temporal")]
    TemporalDurationPrototype,
    #[cfg(feature = "temporal")]
    TemporalPlainTimePrototype,

    // Text processing
    #[cfg(feature = "regexp")]
    RegExpPrototype,

    // Indexed collections
    ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    TypedArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Int8ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Uint8ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Uint8ClampedArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Int16ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Uint16ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Int32ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Uint32ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    BigInt64ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    BigUint64ArrayPrototype,
    #[cfg(feature = "proposal-float16array")]
    Float16ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Float32ArrayPrototype,
    #[cfg(feature = "array-buffer")]
    Float64ArrayPrototype,

    // Keyed collections
    MapPrototype,
    #[cfg(feature = "set")]
    SetPrototype,
    #[cfg(feature = "weak-refs")]
    WeakMapPrototype,
    #[cfg(feature = "weak-refs")]
    WeakSetPrototype,

    // Structured data
    #[cfg(feature = "array-buffer")]
    ArrayBufferPrototype,
    #[cfg(feature = "shared-array-buffer")]
    SharedArrayBufferPrototype,
    #[cfg(feature = "array-buffer")]
    DataViewPrototype,
    #[cfg(feature = "atomics")]
    AtomicsObject,
    #[cfg(feature = "json")]
    JSONObject,

    // Managing memory
    #[cfg(feature = "weak-refs")]
    WeakRefPrototype,
    FinalizationRegistryPrototype,

    // Control abstraction objects
    IteratorPrototype,
    ArrayIteratorPrototype,
    // For-In Iterator objects are never directly accessible to ECMAScript code
    // ForInIteratorPrototype,
    AsyncIteratorPrototype,
    // Note: The AsyncFromSyncIteratorPrototype cannot be observed.
    // AsyncFromSyncIteratorPrototype,
    // The %AsyncGeneratorPrototype% object is %AsyncGeneratorFunction.prototype.prototype%.
    // AsyncGeneratorFunctionPrototypePrototype,
    MapIteratorPrototype,
    #[cfg(feature = "set")]
    SetIteratorPrototype,
    PromisePrototype,
    StringIteratorPrototype,
    GeneratorFunctionPrototype,
    // The %GeneratorPrototype% object is %GeneratorFunction.prototype.prototype%.
    // GeneratorFunctionPrototypePrototype,
    AsyncGeneratorFunctionPrototype,
    GeneratorPrototype,
    AsyncGeneratorPrototype,
    AsyncFunctionPrototype,

    // Reflection
    ReflectObject,

    // Errors subtypes
    AggregateErrorPrototype,
    EvalErrorPrototype,
    RangeErrorPrototype,
    ReferenceErrorPrototype,
    SyntaxErrorPrototype,
    TypeErrorPrototype,

    // Others
    URIErrorPrototype,
    #[cfg(feature = "regexp")]
    RegExpStringIteratorPrototype,
}
#[cfg(feature = "regexp")]
pub(crate) const LAST_INTRINSIC_OBJECT_INDEX: IntrinsicObjectIndexes =
    IntrinsicObjectIndexes::RegExpStringIteratorPrototype;
#[cfg(not(feature = "regexp"))]
pub(crate) const LAST_INTRINSIC_OBJECT_INDEX: IntrinsicObjectIndexes =
    IntrinsicObjectIndexes::URIErrorPrototype;

#[repr(u32)]
#[derive(Debug, Clone, Copy)]
#[allow(clippy::enum_variant_names)]
pub(crate) enum IntrinsicPrimitiveObjectIndexes {
    BooleanPrototype,
    NumberPrototype,
    StringPrototype,
}
const LAST_INTRINSIC_PRIMITIVE_OBJECT_INDEX: IntrinsicPrimitiveObjectIndexes =
    IntrinsicPrimitiveObjectIndexes::StringPrototype;

#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum IntrinsicConstructorIndexes {
    // +===============================================+
    // | Then the list of constructor function objects |
    // +===============================================+

    // Fundamental objects
    Object,
    Function,
    FunctionPrototype,
    Boolean,
    Symbol,
    Error,

    // Numbers and dates
    Number,
    BigInt,
    #[cfg(feature = "date")]
    Date,
    #[cfg(feature = "temporal")]
    TemporalInstant,
    #[cfg(feature = "temporal")]
    TemporalDuration,
    #[cfg(feature = "temporal")]
    TemporalPlainTime,

    // Text processing
    String,
    #[cfg(feature = "regexp")]
    RegExp,

    // Indexed collections
    Array,
    #[cfg(feature = "array-buffer")]
    TypedArray,
    #[cfg(feature = "array-buffer")]
    Int8Array,
    #[cfg(feature = "array-buffer")]
    Uint8Array,
    #[cfg(feature = "array-buffer")]
    Uint8ClampedArray,
    #[cfg(feature = "array-buffer")]
    Int16Array,
    #[cfg(feature = "array-buffer")]
    Uint16Array,
    #[cfg(feature = "array-buffer")]
    Int32Array,
    #[cfg(feature = "array-buffer")]
    Uint32Array,
    #[cfg(feature = "array-buffer")]
    BigInt64Array,
    #[cfg(feature = "array-buffer")]
    BigUint64Array,
    #[cfg(feature = "proposal-float16array")]
    Float16Array,
    #[cfg(feature = "array-buffer")]
    Float32Array,
    #[cfg(feature = "array-buffer")]
    Float64Array,

    // Keyed collections
    Map,
    #[cfg(feature = "set")]
    Set,
    #[cfg(feature = "weak-refs")]
    WeakMap,
    #[cfg(feature = "weak-refs")]
    WeakSet,

    // Structured data
    #[cfg(feature = "array-buffer")]
    ArrayBuffer,
    #[cfg(feature = "shared-array-buffer")]
    SharedArrayBuffer,
    #[cfg(feature = "array-buffer")]
    DataView,

    // Managing memory
    #[cfg(feature = "weak-refs")]
    WeakRef,
    FinalizationRegistry,

    // Control abstraction objects
    Iterator,
    Promise,
    GeneratorFunction,
    AsyncGeneratorFunction,
    AsyncFunction,

    // Reflection
    Proxy,

    // Errors subtypes
    AggregateError,
    EvalError,
    RangeError,
    ReferenceError,
    SyntaxError,
    TypeError,

    // Others
    URIError,
}
pub(crate) const LAST_INTRINSIC_CONSTRUCTOR_INDEX: IntrinsicConstructorIndexes =
    IntrinsicConstructorIndexes::URIError;

#[repr(u32)]
#[derive(Debug, Clone, Copy)]
pub(crate) enum IntrinsicFunctionIndexes {
    // +===================================================================================+
    // | Plain functions: These do not have a corresponding object index reserved for them |
    // +===================================================================================+
    ArrayPrototypeSort,
    ArrayPrototypeToString,
    ArrayPrototypeValues,
    #[cfg(feature = "date")]
    DatePrototypeToUTCString,
    DecodeURI,
    DecodeURIComponent,
    EncodeURI,
    EncodeURIComponent,
    #[cfg(feature = "annex-b-global")]
    Escape,
    Eval,
    GeneratorFunctionPrototypePrototypeNext,
    IsFinite,
    IsNaN,
    MapPrototypeEntries,
    ObjectPrototypeToString,
    ParseFloat,
    ParseInt,
    #[cfg(feature = "regexp")]
    RegExpPrototypeExec,
    #[cfg(feature = "set")]
    SetPrototypeValues,
    StringPrototypeTrimEnd,
    StringPrototypeTrimStart,
    ThrowTypeError,
    #[cfg(feature = "array-buffer")]
    TypedArrayPrototypeValues,
    #[cfg(feature = "annex-b-global")]
    Unescape,
}
#[cfg(feature = "annex-b-global")]
pub(crate) const LAST_INTRINSIC_FUNCTION_INDEX: IntrinsicFunctionIndexes =
    IntrinsicFunctionIndexes::Unescape;
#[cfg(all(not(feature = "annex-b-global"), feature = "array-buffer"))]
pub(crate) const LAST_INTRINSIC_FUNCTION_INDEX: IntrinsicFunctionIndexes =
    IntrinsicFunctionIndexes::TypedArrayPrototypeValues;
#[cfg(all(not(feature = "annex-b-global"), not(feature = "array-buffer")))]
pub(crate) const LAST_INTRINSIC_FUNCTION_INDEX: IntrinsicFunctionIndexes =
    IntrinsicFunctionIndexes::ThrowTypeError;

impl IntrinsicObjectIndexes {
    pub(crate) const OBJECT_INDEX_OFFSET: u32 = 0;
}

impl IntrinsicPrimitiveObjectIndexes {
    pub(crate) const OBJECT_INDEX_OFFSET: u32 =
        IntrinsicObjectIndexes::OBJECT_INDEX_OFFSET + LAST_INTRINSIC_OBJECT_INDEX as u32 + 1;
    pub(crate) const PRIMITIVE_OBJECT_INDEX_OFFSET: u32 = 0;
}

impl IntrinsicConstructorIndexes {
    pub(crate) const OBJECT_INDEX_OFFSET: u32 = IntrinsicPrimitiveObjectIndexes::OBJECT_INDEX_OFFSET
        + LAST_INTRINSIC_PRIMITIVE_OBJECT_INDEX as u32
        + 1;
    pub(crate) const BUILTIN_FUNCTION_INDEX_OFFSET: u32 = 0;
}

impl IntrinsicFunctionIndexes {
    pub(crate) const BUILTIN_FUNCTION_INDEX_OFFSET: u32 =
        IntrinsicConstructorIndexes::BUILTIN_FUNCTION_INDEX_OFFSET
            + LAST_INTRINSIC_CONSTRUCTOR_INDEX as u32
            + 1;
}

pub(crate) const fn intrinsic_object_count() -> usize {
    LAST_INTRINSIC_OBJECT_INDEX as usize
        + 1
        + LAST_INTRINSIC_PRIMITIVE_OBJECT_INDEX as usize
        + 1
        + LAST_INTRINSIC_CONSTRUCTOR_INDEX as usize
        + 1
}

pub(crate) const fn intrinsic_primitive_object_count() -> usize {
    LAST_INTRINSIC_PRIMITIVE_OBJECT_INDEX as usize + 1
}

pub(crate) const fn intrinsic_function_count() -> usize {
    LAST_INTRINSIC_CONSTRUCTOR_INDEX as usize + 1 + LAST_INTRINSIC_FUNCTION_INDEX as usize + 1
}

/// Most commonly needed Object Shapes; these get created as part of Realm
/// initialisation.
///
/// Other shapes are created on-demand.
#[derive(Debug, Clone, Copy)]
#[repr(u32)]
pub(crate) enum IntrinsicObjectShapes {
    Object,
    Array,
    Number,
    String,
}

impl IntrinsicObjectShapes {
    pub(crate) const fn get_object_shape_index(self, base: ObjectShape) -> ObjectShape<'static> {
        ObjectShape::from_non_zero(
            NonZeroU32::new(self as u32 + base.get_index_u32_const() + 1).unwrap(),
        )
    }

    pub(crate) const fn get_proto_intrinsic(self) -> ProtoIntrinsics {
        match self {
            Self::Object => ProtoIntrinsics::Object,
            Self::Array => ProtoIntrinsics::Array,
            Self::Number => ProtoIntrinsics::Number,
            Self::String => ProtoIntrinsics::String,
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub(crate) enum WellKnownSymbols {
    AsyncIterator,
    HasInstance,
    IsConcatSpreadable,
    Iterator,
    #[cfg(feature = "regexp")]
    Match,
    #[cfg(feature = "regexp")]
    MatchAll,
    #[cfg(feature = "regexp")]
    Replace,
    #[cfg(feature = "regexp")]
    Search,
    Species,
    #[cfg(feature = "regexp")]
    Split,
    ToPrimitive,
    ToStringTag,
    Unscopables,
}

impl From<WellKnownSymbols> for Value<'_> {
    fn from(value: WellKnownSymbols) -> Self {
        Value::Symbol(value.into())
    }
}

impl From<WellKnownSymbols> for PropertyKey<'static> {
    fn from(value: WellKnownSymbols) -> Self {
        PropertyKey::Symbol(value.into())
    }
}

impl TryFrom<Symbol<'_>> for WellKnownSymbols {
    type Error = ();

    fn try_from(value: Symbol<'_>) -> Result<Self, Self::Error> {
        const ASYNCITERATOR: u32 = WellKnownSymbols::AsyncIterator as u32;
        const HASINSTANCE: u32 = WellKnownSymbols::HasInstance as u32;
        const ISCONCATSPREADABLE: u32 = WellKnownSymbols::IsConcatSpreadable as u32;
        const ITERATOR: u32 = WellKnownSymbols::Iterator as u32;
        const MATCH: u32 = WellKnownSymbols::Match as u32;
        const MATCHALL: u32 = WellKnownSymbols::MatchAll as u32;
        const REPLACE: u32 = WellKnownSymbols::Replace as u32;
        const SEARCH: u32 = WellKnownSymbols::Search as u32;
        const SPECIES: u32 = WellKnownSymbols::Species as u32;
        const SPLIT: u32 = WellKnownSymbols::Split as u32;
        const TOPRIMITIVE: u32 = WellKnownSymbols::ToPrimitive as u32;
        const TOSTRINGTAG: u32 = WellKnownSymbols::ToStringTag as u32;
        const UNSCOPABLES: u32 = WellKnownSymbols::Unscopables as u32;
        match value.get_index_u32() {
            ASYNCITERATOR => Ok(Self::AsyncIterator),
            HASINSTANCE => Ok(Self::HasInstance),
            ISCONCATSPREADABLE => Ok(Self::IsConcatSpreadable),
            ITERATOR => Ok(Self::Iterator),
            #[cfg(feature = "regexp")]
            MATCH => Ok(Self::Match),
            #[cfg(feature = "regexp")]
            MATCHALL => Ok(Self::MatchAll),
            #[cfg(feature = "regexp")]
            REPLACE => Ok(Self::Replace),
            #[cfg(feature = "regexp")]
            SEARCH => Ok(Self::Search),
            SPECIES => Ok(Self::Species),
            #[cfg(feature = "regexp")]
            SPLIT => Ok(Self::Split),
            TOPRIMITIVE => Ok(Self::ToPrimitive),
            TOSTRINGTAG => Ok(Self::ToStringTag),
            UNSCOPABLES => Ok(Self::Unscopables),
            _ => Err(()),
        }
    }
}

#[cfg(test)]
pub(crate) const LAST_WELL_KNOWN_SYMBOL_INDEX: u32 = WellKnownSymbols::Unscopables as u32;