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
// 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/.

mod abstract_operations;
mod data;

pub(crate) use abstract_operations::*;
pub(crate) use data::*;

use crate::{
    ecmascript::{
        Agent, JsResult, ProtoIntrinsics, TryResult,
        types::{
            BUILTIN_STRING_MEMORY, InternalMethods, InternalSlots, OrdinaryObject,
            PropertyDescriptor, PropertyKey, SetResult, String, TryGetResult, TryHasResult, Value,
            object_handle,
        },
        unwrap_try,
    },
    engine::{Bindable, GcScope, NoGcScope},
    heap::{
        ArenaAccess, ArenaAccessMut, BaseIndex, CompactionLists, CreateHeapData, Heap,
        HeapMarkAndSweep, HeapSweepWeakReference, ObjectEntry, ObjectEntryPropertyDescriptor,
        WorkQueues, arena_vec_access,
    },
};
use oxc_ast::ast::RegExpFlags;
use wtf8::Wtf8Buf;

use super::ordinary::{
    PropertyLookupCache, ordinary_get_own_property, ordinary_has_property, ordinary_set,
    ordinary_try_get, ordinary_try_has_property, ordinary_try_set,
};

/// ## [22.2 RegExp (Regular Expression) Objects](https://tc39.es/ecma262/#sec-regexp-regular-expression-objects)
///
/// A RegExp object contains a regular expression and the associated flags.
///
/// > NOTE: The form and functionality of regular expressions is modelled after
/// > the regular expression facility in the Perl 5 programming language.
///
/// ## Support status
///
/// `RegExp` in Nova does not currently conform to the ECMAScript specification.
/// The implementation does not support lookaheads, lookbehinds, or
/// backreferences. It is always in UTF-8 / Unicode sets mode, does not support
/// RegExp patterns containing unpaired surrogates, and its groups are slightly
/// different from what the ECMAScript specification defines. In short: it is
/// not compliant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct RegExp<'a>(BaseIndex<'a, RegExpHeapData<'static>>);
object_handle!(RegExp);
arena_vec_access!(RegExp, 'a, RegExpHeapData, regexps);

impl<'a> RegExp<'a> {
    /// Fast-path for RegExp object debug stringifying; this does not take into
    /// account any prototype-modifications.
    #[inline(always)]
    pub(crate) fn create_regexp_string(self, agent: &Agent) -> Wtf8Buf {
        self.get(agent).create_regexp_string(agent)
    }

    /// ### \[\[OriginalSource]]
    pub(crate) fn original_source(self, agent: &Agent) -> String<'a> {
        self.get(agent).original_source
    }

    /// ### \[\[OriginalFlags]]
    pub(crate) fn original_flags(self, agent: &Agent) -> RegExpFlags {
        self.get(agent).original_flags
    }

    pub(crate) fn set_last_index(
        self,
        agent: &mut Agent,
        last_index: RegExpLastIndex,
        gc: NoGcScope,
    ) -> bool {
        debug_assert!(last_index.is_valid());
        // If we're setting the last index and we have a backing object,
        // then we set the value there first and observe the result.
        if self.get_backing_object(agent).is_some() {
            // Note: The lastIndex is an unconfigurable data property: It
            // cannot be turned into a getter or setter and will thus never
            // call into JavaScript.
            let success = unwrap_try(ordinary_try_set(
                agent,
                self,
                BUILTIN_STRING_MEMORY.lastIndex.to_property_key(),
                last_index.get_value().unwrap().into(),
                self.into(),
                None,
                gc,
            ))
            .into_boolean()
            .unwrap();
            if success {
                // We successfully set the value, so set it in our direct
                // data as well.
                self.get_mut(agent).last_index = last_index;
            }
            success
        } else {
            // Note: lastIndex property is writable, so setting its value
            // always succeeds. We can just set this directly here.
            self.get_mut(agent).last_index = last_index;
            true
        }
    }

    /// ### \[\[LastIndex]]
    ///
    /// This is a custom internal slot that stores the "lastIndex" property of
    /// a RegExp assuming it has an expected value (32-bit unsigned integer or
    /// undefined). The method returns `None` if the property has an unexpected
    /// value, otherwise it returns the length value (0 if value is undefined).
    pub(crate) fn try_get_last_index(self, agent: &Agent) -> Option<u32> {
        let last_index = self.get(agent).last_index.get_value();
        if last_index.is_some() || self.get_backing_object(agent).is_none() {
            Some(last_index.unwrap_or(0))
        } else {
            None
        }
    }
}

impl<'a> InternalSlots<'a> for RegExp<'a> {
    const DEFAULT_PROTOTYPE: ProtoIntrinsics = ProtoIntrinsics::RegExp;

    fn create_backing_object(self, agent: &mut Agent) -> OrdinaryObject<'static> {
        assert!(self.get_backing_object(agent).is_none());
        let prototype = self.internal_prototype(agent).unwrap();
        let last_index = self.get(agent).last_index;
        let backing_object = OrdinaryObject::create_object(
            agent,
            Some(prototype),
            &[ObjectEntry {
                key: BUILTIN_STRING_MEMORY.lastIndex.into(),
                value: ObjectEntryPropertyDescriptor::Data {
                    value: last_index
                        .get_value()
                        .map_or(Value::Undefined, |i| i.into()),
                    writable: true,
                    enumerable: false,
                    configurable: false,
                },
            }],
        )
        .expect("Should perform GC here");
        self.set_backing_object(agent, backing_object);
        backing_object
    }

    #[inline(always)]
    fn get_backing_object(self, agent: &Agent) -> Option<OrdinaryObject<'static>> {
        self.get(agent).object_index.unbind()
    }

    fn set_backing_object(self, agent: &mut Agent, backing_object: OrdinaryObject<'static>) {
        assert!(
            self.get_mut(agent)
                .object_index
                .replace(backing_object.unbind())
                .is_none()
        );
    }
}

impl<'a> InternalMethods<'a> for RegExp<'a> {
    fn try_get_own_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, Option<PropertyDescriptor<'gc>>> {
        if let Some(backing_object) = self.get_backing_object(agent) {
            // If a backing object exists, it's the only one with correct
            // knowledge of all our properties, including lastIndex.
            TryResult::Continue(ordinary_get_own_property(
                agent,
                self.into(),
                backing_object,
                property_key,
                cache,
                gc,
            ))
        } else if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // If no backing object exists, we can turn lastIndex into a
            // PropertyDescriptor statically.
            TryResult::Continue(Some(self.get(agent).last_index.into_property_descriptor()))
        } else {
            TryResult::Continue(None)
        }
    }

    fn try_has_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, TryHasResult<'gc>> {
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // lastIndex always exists
            TryHasResult::Custom(0, self.bind(gc).into()).into()
        } else {
            ordinary_try_has_property(
                agent,
                self.into(),
                self.get_backing_object(agent),
                property_key,
                cache,
                gc,
            )
        }
    }

    fn internal_has_property<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, bool> {
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // lastIndex always exists
            Ok(true)
        } else if let Some(backing_object) = self.get_backing_object(agent) {
            ordinary_has_property(agent, self.into(), backing_object, property_key, gc)
        } else {
            // a. Let parent be ? O.[[GetPrototypeOf]]().
            // Note: We know statically what this ends up doing.
            let parent = agent
                .current_realm_record()
                .intrinsics()
                .get_intrinsic_default_proto(Self::DEFAULT_PROTOTYPE);

            // a. Return ? parent.[[HasProperty]](P).
            parent.internal_has_property(agent, property_key, gc)
        }
    }

    fn try_get<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        receiver: Value,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, TryGetResult<'gc>> {
        // Regardless of the backing object, we might have a valid value
        // for lastIndex.
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into()
            && let Some(last_index) = self.get(agent).last_index.get_value()
        {
            return TryGetResult::Value(last_index.into()).into();
        }
        ordinary_try_get(
            agent,
            self.into(),
            self.get_backing_object(agent),
            property_key,
            receiver,
            cache,
            gc,
        )
    }

    fn internal_get<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        receiver: Value,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Value<'gc>> {
        let property_key = property_key.bind(gc.nogc());
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // Regardless of the backing object, we might have a valid value
            // for lastIndex.
            if let Some(last_index) = self.get(agent).last_index.get_value() {
                return Ok(last_index.into());
            }
        }
        if let Some(backing_object) = self.get_backing_object(agent) {
            backing_object.internal_get(agent, property_key.unbind(), receiver, gc)
        } else {
            // a. Let parent be ? O.[[GetPrototypeOf]]().
            // Note: We know statically what this ends up doing.
            let parent = agent
                .current_realm_record()
                .intrinsics()
                .get_intrinsic_default_proto(Self::DEFAULT_PROTOTYPE);

            // c. Return ? parent.[[Get]](P, Receiver).
            parent.internal_get(agent, property_key.unbind(), receiver, gc)
        }
    }

    fn try_set<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        value: Value,
        receiver: Value,
        cache: Option<PropertyLookupCache>,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, SetResult<'gc>> {
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // If we're setting the last index and we have a backing object,
            // then we set the value there first and observe the result.
            let new_last_index = RegExpLastIndex::from_value(value);
            if self.get_backing_object(agent).is_some() {
                // Note: The lastIndex is an unconfigurable data property: It
                // cannot be turned into a getter or setter and will thus never
                // call into JavaScript.
                let success = unwrap_try(ordinary_try_set(
                    agent,
                    self,
                    property_key,
                    value,
                    receiver,
                    cache,
                    gc,
                ))
                .into_boolean()
                .unwrap();
                if success {
                    // We successfully set the value, so set it in our direct
                    // data as well.
                    self.get_mut(agent).last_index = new_last_index;
                    SetResult::Done.into()
                } else {
                    SetResult::Unwritable.into()
                }
            } else {
                // Note: lastIndex property is writable, so setting its value
                // always succeeds. We can just set this directly here.
                self.get_mut(agent).last_index = new_last_index;
                // If we we set a value that is not a valid index or undefined,
                // we need to create the backing object and set the actual
                // value there.
                if !new_last_index.is_valid() && value.is_undefined() {
                    unwrap_try(self.create_backing_object(agent).try_set(
                        agent,
                        property_key,
                        value,
                        receiver,
                        cache,
                        gc,
                    ));
                }
                SetResult::Done.into()
            }
        } else {
            // If something else is being set, fall back onto the ordinary
            // abstract operation.
            ordinary_try_set(agent, self, property_key, value, receiver, cache, gc)
        }
    }

    fn internal_set<'gc>(
        self,
        agent: &mut Agent,
        property_key: PropertyKey,
        value: Value,
        receiver: Value,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, bool> {
        if property_key == BUILTIN_STRING_MEMORY.lastIndex.into() {
            // Note: lastIndex is an unconfigurable data property: It cannot
            // become a getter or setter and will thus never call into
            // JavaScript.
            Ok(
                unwrap_try(self.try_set(agent, property_key, value, receiver, None, gc.nogc()))
                    .into_boolean()
                    .unwrap(),
            )
        } else {
            // If something else is being set, fall back onto the ordinary
            // abstract operation.
            ordinary_set(agent, self.into(), property_key, value, receiver, gc)
        }
    }

    fn try_own_property_keys<'gc>(
        self,
        agent: &mut Agent,
        gc: NoGcScope<'gc, '_>,
    ) -> TryResult<'gc, Vec<PropertyKey<'gc>>> {
        TryResult::Continue(
            if let Some(backing_object) = self.get_backing_object(agent) {
                // Note: If backing object exists, it also contains the
                // "lastIndex" key so we do not need to add it ourselves.
                unwrap_try(backing_object.try_own_property_keys(agent, gc))
            } else {
                vec![BUILTIN_STRING_MEMORY.lastIndex.into()]
            },
        )
    }
}

impl HeapMarkAndSweep for RegExp<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        queues.regexps.push(*self);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        compactions.regexps.shift_index(&mut self.0);
    }
}

impl HeapSweepWeakReference for RegExp<'static> {
    fn sweep_weak_reference(self, compactions: &CompactionLists) -> Option<Self> {
        compactions.regexps.shift_weak_index(self.0).map(Self)
    }
}

impl<'a> CreateHeapData<RegExpHeapData<'a>, RegExp<'a>> for Heap {
    fn create(&mut self, data: RegExpHeapData<'a>) -> RegExp<'a> {
        self.regexps.push(data.unbind());
        self.alloc_counter += core::mem::size_of::<RegExpHeapData<'static>>();
        RegExp(BaseIndex::last(&self.regexps))
    }
}