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

use core::marker::PhantomData;

use crate::{
    ecmascript::Agent,
    engine::{Bindable, HeapRootCollection, HeapRootRef, NoGcScope, Rootable, ScopeToken},
};

use super::{HeapRootData, RootableCollection};

/// # Scoped heap root
///
/// This type roots a heap-allocated JavaScript engine value for the duration of
/// the current JavaScript call context, roughly corresponding to a native call
/// scope. Stack-allocated values avoid rooting. Rooted values cannot be garbage
/// collected, so accessing the rooted value is always safe within the current
/// call context. This type is intended for cheap rooting of JavaScript Values
/// that need to be used after calling into functions that may trigger garbage
/// collection.
#[derive(Hash, Clone)]
#[repr(transparent)]
#[allow(private_bounds)]
pub struct Scoped<'a, T: 'static + Rootable> {
    pub(crate) inner: T::RootRepr,
    _marker: PhantomData<T>,
    _scope: PhantomData<&'a ScopeToken>,
}

impl<T: 'static + Rootable> core::fmt::Debug for Scoped<'_, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Scoped<{}>", core::any::type_name::<T>())
    }
}

#[allow(private_bounds)]
impl<T: 'static + Rootable> Scoped<'static, T> {
    #[inline(always)]
    pub(crate) const fn from_root_repr(value: T::RootRepr) -> Scoped<'static, T> {
        Self {
            inner: value,
            _marker: PhantomData,
            _scope: PhantomData,
        }
    }
}

/// Trait for rooting handles for the duration of the `'scope` lifetime.
#[allow(private_bounds)]
pub trait Scopable: Rootable + Bindable
where
    for<'a> Self::Of<'a>: Rootable + Bindable,
{
    /// Root this handle for the `'scope` lifetime.
    fn scope<'scope>(
        self,
        agent: &mut Agent,
        gc: NoGcScope<'_, 'scope>,
    ) -> Scoped<'scope, Self::Of<'static>> {
        Scoped::new(agent, self.unbind(), gc)
    }
}

impl<T: Rootable + Bindable> Scopable for T where for<'a> Self::Of<'a>: Rootable + Bindable {}

#[allow(private_bounds)]
impl<'scope, T: Rootable> Scoped<'scope, T> {
    /// Unwrap the Scoped value to get access to the inner RootRepr value of
    /// the wrapped type.
    ///
    /// ## Safety
    ///
    /// The RootRepr does not carry the 'scope lifetime and is thus liable to
    /// become use-after-free. This method should only be used to implement eg.
    /// trivial From-implementations, or TryFrom-like methods.
    pub(crate) unsafe fn into_root_repr(self) -> T::RootRepr {
        self.inner
    }

    /// Create a new `Scoped` from a scopable value.
    pub fn new(agent: &Agent, value: T, _gc: NoGcScope<'_, 'scope>) -> Self {
        let value = match T::to_root_repr(value) {
            Ok(stack_repr) => {
                // The value doesn't need rooting.
                return Self {
                    inner: stack_repr,
                    _marker: PhantomData,
                    _scope: PhantomData,
                };
            }
            Err(heap_data) => heap_data,
        };
        let mut stack_refs = agent.stack_refs.borrow_mut();
        let next_index = stack_refs.len();
        stack_refs.push(value);
        Self {
            inner: T::from_heap_ref(HeapRootRef::from_index(next_index)),
            _marker: PhantomData,
            _scope: PhantomData,
        }
    }

    /// Returns the scoped value from the heap. If the scoped value was at the
    /// top of the scope stack, then this will drop the value from the stack.
    ///
    /// ## Safety
    ///
    /// The scoped value should not be shared with any other piece of code that
    /// is still going to reuse it.
    ///
    /// ## Panics
    ///
    /// Panics if the `Scoped` has been cloned and the clone has been used to
    /// call `take` already.
    #[must_use]
    pub unsafe fn take(self, agent: &Agent) -> T {
        match T::from_root_repr(&self.inner) {
            Ok(value) => value,
            Err(heap_root_ref) => {
                let index = heap_root_ref.to_index();
                let mut stack_refs = agent.stack_refs.borrow_mut();
                let Some(heap_data) = stack_refs.get_mut(index) else {
                    handle_bound_check_failure()
                };
                let heap_data = core::mem::replace(heap_data, HeapRootData::Empty);
                if index == stack_refs.len() - 1 {
                    Self::drop_empty_slots(&mut stack_refs);
                }
                let Some(value) = T::from_heap_data(heap_data) else {
                    handle_invalid_scoped_conversion()
                };
                value
            }
        }
    }

    /// Internal helper function to drop empty slots from the stack. This
    /// method is separate as dropping empty slots should be a reasonably
    /// rare operation.
    fn drop_empty_slots(stack_refs: &mut Vec<HeapRootData>) {
        // We just replaced the last item with an Empty, so we can
        // shorten the stack by at least one slot.
        let last_non_empty_index = stack_refs
            .iter()
            .enumerate()
            .rfind(|(_, v)| !matches!(v, HeapRootData::Empty))
            .map_or(0, |(index, _)| index + 1);
        debug_assert!(last_non_empty_index < stack_refs.len());
        // SAFETY: The last non-empty index is necessarily within
        // the bounds of the vector, so this only shortens it.
        unsafe { stack_refs.set_len(last_non_empty_index) };
    }

    /// Get a copy of the contained scopable value from a `Scoped`.
    ///
    /// # Panics
    ///
    /// Panics if the `Scoped` has been cloned and the clone has been used to
    /// [take] the value out of the slot.
    ///
    /// [take]: Scoped::take
    pub fn get(&self, agent: &Agent) -> T {
        match T::from_root_repr(&self.inner) {
            Ok(value) => value,
            Err(heap_root_ref) => {
                let Some(&heap_data) = agent.stack_refs.borrow().get(heap_root_ref.to_index())
                else {
                    handle_bound_check_failure()
                };
                let Some(value) = T::from_heap_data(heap_data) else {
                    handle_invalid_scoped_conversion()
                };
                value
            }
        }
    }

    // TODO: Make this const once from_root_repr can be made const.
    // For now the inline(always) is our way to hope that this works equally.
    /// Unwrap the Scoped wrapper, exposing the on-stack value contained
    /// within.
    ///
    /// ## Panics
    ///
    /// If the contained value is a heap reference, the method panics.
    #[inline(always)]
    pub fn unwrap(&self) -> T {
        let Ok(value) = T::from_root_repr(&self.inner) else {
            unreachable!("Scoped value was a heap reference")
        };
        value
    }

    /// Replace an existing scoped value on the heap with a new value of the
    /// same type.
    ///
    /// ## Safety
    ///
    /// If the scoped value has been cloned and is still being used, replacing
    /// its value will be observable to the other users and they will likely
    /// find this unexpected.
    ///
    /// This method should only ever be called on scoped values that have not
    /// been shared outside the caller.
    pub unsafe fn replace(&mut self, agent: &Agent, value: T) {
        let heap_data = match T::to_root_repr(value) {
            Ok(stack_repr) => {
                // The value doesn't need rooting.
                let previous = core::mem::replace(
                    self,
                    Self {
                        inner: stack_repr,
                        _marker: PhantomData,
                        _scope: PhantomData,
                    },
                );

                // Let's take the previous value from the heap if it existed.
                // SAFETY: The caller guarantees that the scoped value has not
                // been shared.
                let _ = unsafe { previous.take(agent) };
                return;
            }
            Err(heap_data) => heap_data,
        };
        match T::from_root_repr(&self.inner) {
            Ok(_) => {
                // We do not have an existing slot but now need one.
                let mut stack_refs = agent.stack_refs.borrow_mut();
                let next_index = stack_refs.len();
                stack_refs.push(heap_data);
                *self = Self {
                    inner: T::from_heap_ref(HeapRootRef::from_index(next_index)),
                    _marker: PhantomData,
                    _scope: PhantomData,
                }
            }
            Err(heap_root_ref) => {
                // Existing slot, we can just replace the data.
                let mut stack_refs_borrow = agent.stack_refs.borrow_mut();
                let Some(heap_slot) = stack_refs_borrow.get_mut(heap_root_ref.to_index()) else {
                    handle_bound_check_failure()
                };
                *heap_slot = heap_data;
            }
        }
    }

    /// Replace an existing scoped value on the heap with a new value of a
    /// different type.
    ///
    /// ## Safety
    ///
    /// If the scoped value has been cloned and is still being used, replacing
    /// its value will be observable to the other users and they will likely
    /// find this unexpected and will likely panic from a type mismatch.
    ///
    /// This method should only ever be called on scoped values that have not
    /// been shared outside the caller.
    pub unsafe fn replace_self<U: 'static + Rootable>(
        self,
        agent: &mut Agent,
        value: U,
    ) -> Scoped<'scope, U> {
        let heap_data = match U::to_root_repr(value) {
            Ok(stack_repr) => {
                // Let's take the previous value from the heap if it existed.
                // SAFETY: The caller guarantees that the scoped value has not
                // been shared.
                let _ = unsafe { self.take(agent) };
                // The value doesn't need rooting.
                return Scoped {
                    inner: stack_repr,
                    _marker: PhantomData,
                    _scope: PhantomData,
                };
            }
            Err(heap_data) => heap_data,
        };
        match T::from_root_repr(&self.inner) {
            Ok(_) => {
                // The previous scoped value did not have an heap slot but now
                // need one.
                let mut stack_refs = agent.stack_refs.borrow_mut();
                let next_index = stack_refs.len();
                stack_refs.push(heap_data);
                Scoped {
                    inner: U::from_heap_ref(HeapRootRef::from_index(next_index)),
                    _marker: PhantomData,
                    _scope: PhantomData,
                }
            }
            Err(heap_root_ref) => {
                // Existing slot, we can just replace the data.
                let mut stack_refs_borrow = agent.stack_refs.borrow_mut();
                let Some(heap_slot) = stack_refs_borrow.get_mut(heap_root_ref.to_index()) else {
                    handle_bound_check_failure()
                };
                *heap_slot = heap_data;
                Scoped {
                    inner: U::from_heap_ref(heap_root_ref),
                    _marker: PhantomData,
                    _scope: PhantomData,
                }
            }
        }
    }
}

/// Trait for rooting collections of handles for the duration of the `'scope`
/// lifetime.
#[allow(private_bounds)]
pub trait ScopableCollection: Bindable
where
    Self::Of<'static>: RootableCollection,
{
    /// Root this handle collection for the `'scope` lifetime.
    fn scope<'scope>(
        self,
        agent: &Agent,
        gc: NoGcScope<'_, 'scope>,
    ) -> ScopedCollection<'scope, Self::Of<'static>>;
}

/// # Scoped heap root collection
///
/// This type roots a heap-allocated JavaScript engine value collection for the
/// duration of the current JavaScript call context, roughly corresponding to a
/// native call scope. Rooted values cannot be garbage collected, so accessing
/// the rooted values is always safe within the current call context. This type
/// is intended for cheap rooting of JavaScript Values that need to be used
/// after calling into functions that may trigger garbage collection.
#[derive(Debug, Hash, Clone)]
#[repr(transparent)]
#[allow(private_bounds)]
pub struct ScopedCollection<'a, T: 'static + RootableCollection> {
    /// Index to Agent's stack_ref_collections
    pub(crate) inner: u32,
    _marker: PhantomData<T>,
    _scope: PhantomData<&'a ScopeToken>,
}

#[allow(private_bounds)]
impl<'a, T: 'static + RootableCollection> ScopedCollection<'a, T> {
    /// Create a new ScopedCollection by moving a rootable collection onto the
    /// Agent's heap.
    pub(crate) fn new(agent: &Agent, rootable: T, _gc: NoGcScope<'_, 'a>) -> Self {
        let heap_data = rootable.to_heap_data();
        let inner = u32::try_from(agent.stack_ref_collections.borrow().len())
            .expect("ScopedCollections stack overflowed");
        agent.stack_ref_collections.borrow_mut().push(heap_data);
        Self {
            inner,
            _marker: PhantomData,
            _scope: PhantomData,
        }
    }

    /// Take ownership of the rootable collection from the Agent's heap.
    #[must_use]
    pub(crate) fn take(self, agent: &Agent) -> T {
        let index = self.inner;
        let mut stack_ref_collections = agent.stack_ref_collections.borrow_mut();
        let heap_slot = stack_ref_collections.get_mut(index as usize).unwrap();
        let heap_data = core::mem::replace(heap_slot, HeapRootCollection::Empty);
        if index as usize == stack_ref_collections.len() - 1 {
            Self::drop_empty_slots(&mut stack_ref_collections);
        }
        T::from_heap_data(heap_data)
    }

    /// Internal helper function to drop empty slots from the stack. This
    /// method is separate as dropping empty slots should be a reasonably
    /// rare operation.
    fn drop_empty_slots(stack_ref_collections: &mut Vec<HeapRootCollection>) {
        // We replaced the last stack item with an Empty, so we can shorten
        // the stack by at least one.
        let last_non_empty_index = stack_ref_collections
            .iter()
            .enumerate()
            .rfind(|(_, v)| !v.is_empty())
            .map_or(0, |(index, _)| index + 1);
        debug_assert!(last_non_empty_index < stack_ref_collections.len());
        // SAFETY: The last non-empty index is necessarily within
        // the bounds of the vector, so this only shortens it. The
        // items being dropped are also Empty slots which don't
        // need any drop calls, so this is not a memory leak
        // either.
        unsafe { stack_ref_collections.set_len(last_non_empty_index) };
    }
}

#[cold]
#[inline(never)]
fn handle_invalid_scoped_conversion() -> ! {
    panic!("Attempted to convert mismatched Scoped");
}

#[cold]
#[inline(never)]
fn handle_bound_check_failure() -> ! {
    panic!("Attempted to access dropped Scoped")
}