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
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
// 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 std::ops::ControlFlow;

use wtf8::CodePoint;

use crate::engine::Rootable;

use super::Scoped;

/// # ZST type representing access to the garbage collector.
///
/// Access to a garbage collected type's heap data should mainly require
/// holding a `ContextRef<'gc, GcToken>`. Borrowing the heap data should bind
/// to the `'gc` lifetime.
// Note: non-exhaustive to make sure this is not constructable on the outside.
#[non_exhaustive]
#[derive(Debug)]
pub(crate) struct GcToken;

/// # ZST type representing a JavaScript call scope
///
/// Access to scoped root values should mainly require holding a
/// `ContextRef<'scope, ScopeToken>`. In limited cases, borrowing heap data can
/// bind to the `'scope` lifetime.
// Note: non-exhaustive to make sure this is not constructable on the outside.
#[non_exhaustive]
#[derive(Debug)]
pub(crate) struct ScopeToken;

/// # JavaScript call scope that may trigger garbage collection
///
/// This marker represents access to the JavaScript call stack and specifically
/// gives the call stack the possibility of performing garbage collection.
/// In the engine, most values are by-default not rooted during operations
/// which means that garbage collection invalidates them. This GcScope marker
/// is a way for the borrow checker to ensure that all values are rooted /
/// returned to the heap / registered with the heap before the garbage
/// collector potentially runs.
///
/// In essence, this is a compile-time method of ensuring safepoint garbage
/// collection safety.
#[derive(Debug)]
pub struct GcScope<'a, 'b> {
    /// A GcScope "owns" the GC access: There is only ever one "active" GcToken
    /// in the world at a time. Reborrowing a GcScope binds the previous one,
    /// so its contained GcToken is "inactive" during the lifetime of the
    /// reborrowed one.
    #[expect(dead_code)]
    gc: GcToken,
    /// A GcScope also "owns" the scope access: This is the access to the
    /// Scoped roots stack. This is not yet well-defined but probably only
    /// GC scopes are allowed to shrink the Scoped roots stack.
    #[expect(dead_code)]
    scope: ScopeToken,
    /// We must also keep an exclusive borrow on a GcToken. This enables
    /// various engine values to reborrow this lifetime as shared and that way
    /// have the borrow checker check that those values are not used while
    /// garbage collection may run.
    _gc_marker: PhantomData<&'a mut GcToken>,
    /// We keep a shared borrow on the ScopeToken. This is not yet well-defined
    /// but probably we'll create new ScopeToken borrow lifetimes using the
    /// for<'a> closure trick.
    _scope_marker: PhantomData<&'b ScopeToken>,
}

/// # JavaScript call scope that may not trigger garbage collection
///
/// This marker represents access to the JavaScript call stack in a way that
/// cannot trigger garbage collection. Actions like working with primitive
/// JavaScript Values and accessing non-Proxy object prototypes are examples of
/// actions that can never trigger garbage collection.
///
/// This marker allows performing these sort of actions without rooting other
/// values held on the stack.
#[derive(Debug, Clone, Copy)]
pub struct NoGcScope<'a, 'b> {
    /// A NoGcScope does not own the GC access, and naturally cannot trigger
    /// garbage collection. We keep a shared borrow on this lifetime to ensure
    /// that the GcScope we derive from cannot be used concurrently.
    _gc_marker: PhantomData<&'a GcToken>,
    /// We also don't own scope access. This is not yet well-defined.
    _scope_marker: PhantomData<&'b ScopeToken>,
}

impl<'a, 'b> NoGcScope<'a, 'b> {
    /// If you're intentionally calling this function, you've probably made a
    /// mistake. You already hold a NoGcScope and are trying to it into a
    /// NoGcScope again: there is no need. Just remove this call.
    #[inline(always)]
    #[must_use]
    pub(crate) fn into_nogc(self) -> Self {
        self
    }
}

impl GcToken {
    unsafe fn new() -> Self {
        Self
    }
}

impl ScopeToken {
    unsafe fn new() -> Self {
        Self
    }
}

impl<'a, 'b> GcScope<'a, 'b> {
    /// SAFETY: Only one GcScope root should exist at any point in time.
    ///
    /// The caller must make sure to only create a new root when a new
    /// JavaScript call stack is initialized.
    #[inline]
    pub(crate) unsafe fn create_root() -> (GcToken, ScopeToken) {
        (unsafe { GcToken::new() }, unsafe { ScopeToken::new() })
    }

    #[inline]
    pub(crate) fn new(_: &'a mut GcToken, _: &'b mut ScopeToken) -> Self {
        Self {
            gc: GcToken,
            scope: ScopeToken,
            _gc_marker: PhantomData,
            _scope_marker: PhantomData,
        }
    }

    /// Create a GcScope marker that inherits the current GcScope's lifetimes.
    /// This reborrowing is necessary to ensure that only one GcScope is active
    /// at any point in time, and the existence of the active GcScope binds any
    /// "parent" GcScopes from being used concurrently.
    #[inline]
    pub fn reborrow(&mut self) -> GcScope<'_, 'b> {
        Self {
            gc: GcToken,
            scope: ScopeToken,
            _gc_marker: PhantomData,
            _scope_marker: PhantomData,
        }
    }

    /// Create a GcScope marker that inherits the current GcScope's garbage
    /// collector lifetime but creates a new scope lifetime. This should be
    /// used when deeper JavaScript call stacks are entered.
    #[inline]
    pub(crate) fn subscope(&mut self) -> GcScope<'a, '_> {
        Self {
            gc: GcToken,
            scope: ScopeToken,
            _gc_marker: PhantomData,
            _scope_marker: PhantomData,
        }
    }

    /// Create a NoGcScope marker that is used to bind the garbage collector
    /// lifetime to various engine values. Existence of the NoGcScope is a
    /// build-time proof that garbage collection cannot happen.
    ///
    /// When a garbage collection can happen, the borrow checker will ensure
    /// that all engine values that were bound to the NoGcScope are dropped or
    /// are registered with the heap using Scoped or Global roots.
    #[inline]
    #[must_use]
    pub fn nogc(&self) -> NoGcScope<'_, 'b> {
        NoGcScope::from_gc(self)
    }

    /// Turn a GcScope marker into a NoGcScope. This is otherwise equivalent to
    /// [the `nogc()` method](Self::nogc) with the exception that this consumes
    /// the parent GcScope.
    ///
    /// This is useful when a method ends in a NoGC scope based return within
    /// an if/else branch while another branch still uses the GcScope. The
    /// borrow checker does not like this with the `nogc()` method but allows
    /// it with this method.
    #[inline]
    #[must_use]
    pub fn into_nogc(self) -> NoGcScope<'a, 'b> {
        NoGcScope {
            _gc_marker: PhantomData,
            _scope_marker: PhantomData,
        }
    }
}

impl<'a, 'b> NoGcScope<'a, 'b> {
    #[allow(unknown_lints, gc_scope_is_only_passed_by_value)]
    #[inline]
    pub(crate) fn from_gc(_: &GcScope<'a, 'b>) -> Self {
        Self {
            _gc_marker: PhantomData,
            _scope_marker: PhantomData,
        }
    }
}

/// Method for binding and unbinding garbage collectable values from the
/// garbage collector lifetime. This is a necessary evil for calling and
/// entering functions that contain garbage collector safepoints.
///
/// ## Why is this needed?
///
/// From the borrow checker's point of view, bindable values all alias the
/// "garbage collector reference" contained in `GcScope`. Any function that
/// can trigger garbage collection takes an exclusive garbage collector
/// reference, which then means that passing any bound values would be an
/// aliasing violation. The borrow checker will not allow that and a compile
/// error results. To allow the call to compile, the bindable values must be
/// unbound at the call site.
///
/// Inside the function, the bindable parameter values initially are unbound
/// from the garbage collector lifetime. This means that the borrow checker
/// will not check their usage for use-after-free. To make the borrow checker
/// check them, the values must be bound using the `bind` function.
///
/// ## Safety
///
/// The implementations for both functions must be equivalent to a `memcpy` or,
/// for collections of bindable values, a new collection of bindable values
/// recursively mapped. The end result should be entirely equal to a lifetime
/// transmute on performed on Self. The implementation of the functions
/// themselves are also allowed to be a plain transmute.
///
/// ```rust,compile_fail
/// let result = unsafe { core::mem::transmute::<Value<'a>, Value<'b>(value) };
/// ```
pub unsafe trait Bindable: Sized {
    /// Bound representation of self. This must always be effectively equal to
    /// `Self<'a>`. Note that we cannot write `Self<'a>` directly because
    /// `Self` cannot have lifetime parameters attached to it.
    ///
    /// ## Safety
    ///
    /// This type is the most important part of this trait. It _must be_
    /// correctly set to be effectively equal to `Self<'a>`.
    ///
    /// ## Examples
    ///
    /// This is the only correct way to define the type:
    ///
    /// ```rust
    /// use nova_vm::engine::{Bindable, NoGcScope};
    /// struct MyType<'a>(std::marker::PhantomData<&'a ()>);
    /// unsafe impl Bindable for MyType<'_> {
    ///   type Of<'a> = MyType<'a>;
    ///
    ///   #[inline(always)]
    ///   fn unbind(self) -> Self::Of<'static> {
    ///     unsafe { core::mem::transmute::<Self, Self::Of<'static>>(self) }
    ///   }
    ///
    ///   #[inline(always)]
    ///   fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
    ///     unsafe { core::mem::transmute::<Self, Self::Of<'a>>(self) }
    ///   }
    /// }
    /// ```
    type Of<'a>;

    /// Unbind this value from the garbage collector lifetime. This is
    /// necessary for eg. when using the value as a parameter in a call that
    /// can perform garbage collection.
    ///
    /// This function's implementation must be equivalent to a (recursive)
    /// `memcpy`. The intention is that the entire function optimises to
    /// nothing in the final binary.
    ///
    /// ## Safety
    ///
    /// This function is conceptually should only be used for one of the following actions:
    ///
    /// 1. Unbind a value to allow passing it as a parameter.
    /// 2. Unbind a value to allow returning as a result, though this should be
    ///    avoided if possible.
    /// 3. Temporarily unbind a value to allow turning a `GcScope` into a
    ///    `NoGcScope`, and immediately rebind it with the `NoGcScope`.
    ///
    /// ## Examples
    ///
    /// ```rust,ignore
    /// // Unbind a value to allow passing it as a parameter.
    /// function_call(agent, value.unbind(), gc.reborrow());
    /// ```
    ///
    /// ```rust,ignore
    /// // Unbind a value to allow returning as a result.
    /// let result = function_call(agent, gc.reborrow());
    /// if cond {
    ///   // Note: `result` is bound to a local temporary created in
    ///   // `gc.reborrow()`, which is why this will not work without unbind.
    ///   return Ok(result.unbind());
    /// }
    /// ```
    ///
    /// ```rust,ignore
    /// // Unbind a value temporarily to immediately rebind it with a
    /// // `NoGcScope`.
    /// let result = function_call(agent, gc.reborrow()).unbind();
    /// let gc = gc.into_nogc();
    /// let result = result.bind(gc);
    /// ```
    ///
    /// *Incrrect* usage of this function: unbind a value into a variable
    /// without immediate rebinding.
    /// ```rust,ignore
    /// let result = try_function_call(agent, gc.nogc()).unbind();
    /// function_call(agent, result, gc.reborrow());
    /// // Note: `result` is use-after-free because of above `gc.reborrow()`.
    /// return Ok(result);
    /// ```
    fn unbind(self) -> Self::Of<'static>;

    /// Bind this value to the garbage collector lifetime. This is necessary to
    /// enable the borrow checker to check that bindable values are not
    /// use-after-free.
    ///
    ///
    ///
    /// This function's implementation must be equivalent to a (recursive)
    /// `memcpy`. The intention is that the entire function optimises to
    /// nothing in the final binary.
    ///
    /// ## Safety
    ///
    /// This function is always safe to use. It is required to call it in the
    /// following places:
    ///
    /// 1. Bind every bindable argument when a function with a garbage
    ///    collector safepoint is entered.
    /// 2. Bind a bindable value when it is copied from the engine heap.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use nova_vm::ecmascript::{Agent, ArgumentsList, JsResult, Value};
    /// use nova_vm::engine::{GcScope, Bindable};
    /// fn function_call<'gc>(
    ///   agent: &mut Agent,
    ///   this_value: Value,
    ///   arguments: ArgumentsList,
    ///   gc: GcScope<'gc, '_>
    /// ) -> Value<'gc> {
    ///   // Bind every bindable argument when a function with a garbage
    ///   // collector safepoint is entered.
    ///   // Note: Because this function takes `GcScope`, it should contain a
    ///   // safepoint.
    ///   let nogc = gc.nogc();
    ///   let this_value = this_value.bind(nogc);
    ///   let arg0 = arguments.get(0).bind(nogc);
    ///   // ...
    ///   Value::Undefined
    /// }
    /// ```
    ///
    /// ```rust,ignore
    /// // Bind a bindable value when it is copied from the engine heap.
    /// let first = array.get(agent).as_slice()[0].bind(gc.nogc());
    /// ```
    ///
    /// *Incorrect* usage of this function: skip binding arguments when a
    /// function with a garbage collector safepoint is entered.
    /// ```rust
    /// use nova_vm::ecmascript::{ArgumentsList, Agent, JsResult, Value};
    /// use nova_vm::engine::{GcScope, Bindable};
    /// fn function_call<'gc>(
    ///   agent: &mut Agent,
    ///   this_value: Value,
    ///   arguments: ArgumentsList,
    ///   mut gc: GcScope<'gc, '_>
    /// ) -> Value<'gc> {
    ///   // Note: This is still technically fine due to no preceding `GcScope`
    ///   // usage.
    ///   let string = this_value.to_string(agent, gc.reborrow());
    ///   // Note: `arguments` is use-after-free because of above
    ///   // `gc.reborrow()`.
    ///   let value = arguments.get(0).bind(gc.nogc());
    ///   // ...
    ///   Value::Undefined
    /// }
    /// ```
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a>;
}

macro_rules! bindable_handle {
    ($self:ident) => {
        // SAFETY: Bindable handle.
        unsafe impl crate::engine::Bindable for $self<'_> {
            type Of<'a> = $self<'a>;

            #[inline(always)]
            fn unbind(self) -> Self::Of<'static> {
                unsafe { core::mem::transmute::<Self, Self::Of<'static>>(self) }
            }

            #[inline(always)]
            fn bind<'a>(self, _: crate::engine::NoGcScope<'a, '_>) -> Self::Of<'a> {
                unsafe { core::mem::transmute::<Self, Self::Of<'a>>(self) }
            }
        }
    };
}
pub(crate) use bindable_handle;

macro_rules! trivially_bindable {
    ($self:ty) => {
        // SAFETY: Trivially safe.
        unsafe impl crate::engine::Bindable for $self {
            type Of<'a> = Self;

            #[inline(always)]
            fn unbind(self) -> Self::Of<'static> {
                self
            }

            #[inline(always)]
            fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
                self
            }
        }
    };
}
pub(crate) use trivially_bindable;

trivially_bindable!(());
trivially_bindable!(bool);
trivially_bindable!(i8);
trivially_bindable!(u8);
trivially_bindable!(i16);
trivially_bindable!(u16);
trivially_bindable!(i32);
trivially_bindable!(u32);
trivially_bindable!(i64);
trivially_bindable!(u64);
trivially_bindable!(i128);
trivially_bindable!(u128);
trivially_bindable!(isize);
trivially_bindable!(usize);
#[cfg(feature = "proposal-float16array")]
trivially_bindable!(f16);
trivially_bindable!(f32);
trivially_bindable!(f64);
trivially_bindable!(CodePoint);

// SAFETY: Trivially safe.
unsafe impl<'b, T: 'static + Rootable> Bindable for Scoped<'b, T> {
    type Of<'a> = Scoped<'b, T>;

    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        self
    }

    #[inline(always)]
    fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        self
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable> Bindable for Option<T> {
    type Of<'a> = Option<T::Of<'a>>;

    // Note: Option is simple enough to always inline the code.
    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        self.map(T::unbind)
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        self.map(|t| t.bind(gc))
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable> Bindable for Box<T> {
    type Of<'a> = Box<T::Of<'a>>;

    // Note: Box is simple enough to always inline the code.
    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        unsafe { std::mem::transmute::<_, _>(self) }
    }

    #[inline(always)]
    fn bind<'a>(self, _: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        unsafe { std::mem::transmute::<_, _>(self) }
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, E: Bindable> Bindable for Result<T, E> {
    type Of<'a> = Result<T::Of<'a>, E::Of<'a>>;

    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        self.map(T::unbind).map_err(E::unbind)
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        self.map(|t| t.bind(gc)).map_err(|e| e.bind(gc))
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, E: Bindable> Bindable for ControlFlow<T, E> {
    type Of<'a> = ControlFlow<T::Of<'a>, E::Of<'a>>;

    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        match self {
            ControlFlow::Continue(c) => ControlFlow::Continue(c.unbind()),
            ControlFlow::Break(b) => ControlFlow::Break(b.unbind()),
        }
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        match self {
            ControlFlow::Continue(c) => ControlFlow::Continue(c.bind(gc)),
            ControlFlow::Break(b) => ControlFlow::Break(b.bind(gc)),
        }
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable> Bindable for Vec<T> {
    type Of<'a> = Vec<T::Of<'a>>;

    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        const {
            // Note: These checks do not guarantee that the Vec transmute is
            // truly safe: Vec is free to rearrange its fields if its type
            // parameter changes. These checks will only catch flagrant misuse.
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime out of the T's in the Vec.
        unsafe { core::mem::transmute::<Vec<T>, Vec<T::Of<'static>>>(self) }
    }

    #[inline(always)]
    fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            // Note: These checks do not guarantee that the Vec transmute is
            // truly safe: Vec is free to rearrange its fields if its type
            // parameter changes. These checks will only catch flagrant misuse.
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime out of the T's in the Vec.
        unsafe { core::mem::transmute::<Vec<T>, Vec<T::Of<'a>>>(self) }
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable> Bindable for Box<[T]> {
    type Of<'gc> = Box<[T::Of<'gc>]>;

    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime out of the T's in the slice.
        unsafe { core::mem::transmute::<Box<[T]>, Box<[T::Of<'static>]>>(self) }
    }

    #[inline(always)]
    fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime into the T's in the slice.
        unsafe { core::mem::transmute::<Box<[T]>, Box<[T::Of<'a>]>>(self) }
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<'slice, T: Bindable> Bindable for &'slice [T]
where
    for<'gc> <T as Bindable>::Of<'gc>: 'slice,
{
    type Of<'gc> = &'slice [T::Of<'gc>];

    fn unbind(self) -> Self::Of<'static> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime out of the T's in the slice.
        unsafe { core::mem::transmute::<&'slice [T], &'slice [T::Of<'static>]>(self) }
    }

    #[inline(always)]
    fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        const {
            assert!(core::mem::size_of::<T>() == core::mem::size_of::<T::Of<'_>>());
            assert!(core::mem::align_of::<T>() == core::mem::align_of::<T::Of<'_>>());
        }
        // SAFETY: We assume that T properly implements Bindable. In that case
        // we can safely transmute the lifetime into the T's in the slice.
        unsafe { core::mem::transmute::<&'slice [T], &'slice [T::Of<'a>]>(self) }
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, U: Bindable> Bindable for (T, U) {
    type Of<'gc> = (T::Of<'gc>, U::Of<'gc>);

    fn unbind(self) -> Self::Of<'static> {
        (self.0.unbind(), self.1.unbind())
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        (self.0.bind(gc), self.1.bind(gc))
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, U: Bindable, V: Bindable> Bindable for (T, U, V) {
    type Of<'gc> = (T::Of<'gc>, U::Of<'gc>, V::Of<'gc>);

    fn unbind(self) -> Self::Of<'static> {
        (self.0.unbind(), self.1.unbind(), self.2.unbind())
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        (self.0.bind(gc), self.1.bind(gc), self.2.bind(gc))
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, U: Bindable, V: Bindable, W: Bindable> Bindable for (T, U, V, W) {
    type Of<'gc> = (T::Of<'gc>, U::Of<'gc>, V::Of<'gc>, W::Of<'gc>);

    fn unbind(self) -> Self::Of<'static> {
        (
            self.0.unbind(),
            self.1.unbind(),
            self.2.unbind(),
            self.3.unbind(),
        )
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        (
            self.0.bind(gc),
            self.1.bind(gc),
            self.2.bind(gc),
            self.3.bind(gc),
        )
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, U: Bindable, V: Bindable, W: Bindable, X: Bindable> Bindable
    for (T, U, V, W, X)
{
    type Of<'gc> = (T::Of<'gc>, U::Of<'gc>, V::Of<'gc>, W::Of<'gc>, X::Of<'gc>);

    fn unbind(self) -> Self::Of<'static> {
        (
            self.0.unbind(),
            self.1.unbind(),
            self.2.unbind(),
            self.3.unbind(),
            self.4.unbind(),
        )
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        (
            self.0.bind(gc),
            self.1.bind(gc),
            self.2.bind(gc),
            self.3.bind(gc),
            self.4.bind(gc),
        )
    }
}

// SAFETY: The blanket impls are safe if the implementors are.
unsafe impl<T: Bindable, U: Bindable, V: Bindable, W: Bindable, X: Bindable, Y: Bindable> Bindable
    for (T, U, V, W, X, Y)
{
    type Of<'gc> = (
        T::Of<'gc>,
        U::Of<'gc>,
        V::Of<'gc>,
        W::Of<'gc>,
        X::Of<'gc>,
        Y::Of<'gc>,
    );

    fn unbind(self) -> Self::Of<'static> {
        (
            self.0.unbind(),
            self.1.unbind(),
            self.2.unbind(),
            self.3.unbind(),
            self.4.unbind(),
            self.5.unbind(),
        )
    }

    #[inline(always)]
    fn bind<'a>(self, gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        (
            self.0.bind(gc),
            self.1.bind(gc),
            self.2.bind(gc),
            self.3.bind(gc),
            self.4.bind(gc),
            self.5.bind(gc),
        )
    }
}