forked from denoland/rusty_v8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.rs
1967 lines (1784 loc) · 70.1 KB
/
scope.rs
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2021 the Deno authors. All rights reserved. MIT license.
//! This module's public API exports a number of 'scope' types.
//!
//! These types carry information about the state of the V8 Isolate, as well as
//! lifetimes for certain (return) values. More specialized scopes typically
//! deref to more generic scopes, and ultimately they all deref to `Isolate`.
//!
//! The scope types in the public API are all pointer wrappers, and they all
//! point at a heap-allocated struct `data::ScopeData`. `ScopeData` allocations
//! are never shared between scopes; each Handle/Context/CallbackScope gets
//! its own instance.
//!
//! Notes about the available scope types:
//! See also the tests at the end of this file.
//!
//! - `HandleScope<'s, ()>`
//! - 's = lifetime of local handles created in this scope, and of the scope
//! itself.
//! - This type is returned when a HandleScope is constructed from a direct
//! reference to an isolate (`&mut Isolate` or `&mut OwnedIsolate`).
//! - A `Context` is _not_ available. Only certain types JavaScript values can
//! be created: primitive values, templates, and instances of `Context`.
//! - Derefs to `Isolate`.
//!
//! - `HandleScope<'s>`
//! - 's = lifetime of local handles created in this scope, and of the scope
//! itself.
//! - A `Context` is available; any type of value can be created.
//! - Derefs to `HandleScope<'s, ()>`
//!
//! - `ContextScope<'s, P>`
//! - 's = lifetime of the scope itself.
//! - A `Context` is available; any type of value can be created.
//! - Derefs to `P`.
//! - When constructed as the child of a `HandleScope<'a, ()>`, the returned
//! type is `ContextScope<'s, HandleScope<'p>>`. In other words, the parent
//! HandleScope gets an upgrade to indicate the availability of a `Context`.
//! - When a new scope is constructed inside this type of scope, the
//! `ContextScope` wrapper around `P` is erased first, which means that the
//! child scope is set up as if it had been created with `P` as its parent.
//!
//! - `EscapableHandleScope<'s, 'e>`
//! - 's = lifetime of local handles created in this scope, and of the scope
//! itself.
//! - 'e = lifetime of the HandleScope that will receive the local handle that
//! is created by `EscapableHandleScope::escape()`.
//! - A `Context` is available; any type of value can be created.
//! - Derefs to `HandleScope<'s>`.
//!
//! - `TryCatch<'s, P>`
//! - 's = lifetime of the TryCatch scope.
//! - `P` is either a `HandleScope` or an `EscapableHandleScope`. This type
//! also determines for how long the values returned by `TryCatch` methods
//! `exception()`, `message()`, and `stack_trace()` are valid.
//! - Derefs to `P`.
//! - Creating a new scope inside the `TryCatch` block makes its methods
//! inaccessible until the inner scope is dropped. However, the `TryCatch`
//! object will nonetheless catch all exception thrown during its lifetime.
//!
//! - `CallbackScope<'s, ()>`
//! - 's = lifetime of local handles created in this scope, and the value
//! returned from the callback, and of the scope itself.
//! - A `Context` is _not_ available. Only certain types JavaScript values can
//! be created: primitive values, templates, and instances of `Context`.
//! - Derefs to `HandleScope<'s, ()>`.
//! - This scope type is only to be constructed inside embedder defined
//! callbacks when these are called by V8.
//! - When a scope is created inside, type is erased to `HandleScope<'s, ()>`.
//!
//! - `CallbackScope<'s>`
//! - 's = lifetime of local handles created in this scope, and the value
//! returned from the callback, and of the scope itself.
//! - A `Context` is available; any type of value can be created.
//! - Derefs to `HandleScope<'s>`.
//! - This scope type is only to be constructed inside embedder defined
//! callbacks when these are called by V8.
//! - When a scope is created inside, type is erased to `HandleScope<'s>`.
use std::alloc::alloc;
use std::alloc::Layout;
use std::any::type_name;
use std::cell::Cell;
use std::convert::TryInto;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::num::NonZeroUsize;
use std::ops::Deref;
use std::ops::DerefMut;
use std::ptr;
use std::ptr::NonNull;
use crate::function::FunctionCallbackInfo;
use crate::function::PropertyCallbackInfo;
use crate::Context;
use crate::Data;
use crate::DataError;
use crate::Handle;
use crate::Isolate;
use crate::Local;
use crate::Message;
use crate::Object;
use crate::OwnedIsolate;
use crate::Primitive;
use crate::PromiseRejectMessage;
use crate::Value;
/// Stack-allocated class which sets the execution context for all operations
/// executed within a local scope. After entering a context, all code compiled
/// and run is compiled and run in this context.
#[derive(Debug)]
pub struct ContextScope<'s, P> {
_data: NonNull<data::ScopeData>,
_phantom: PhantomData<&'s mut P>,
}
impl<'s, P: param::NewContextScope<'s>> ContextScope<'s, P> {
#[allow(clippy::new_ret_no_self)]
pub fn new(param: &'s mut P, context: Local<Context>) -> P::NewScope {
let scope_data = param.get_scope_data_mut();
if scope_data.get_isolate_ptr()
!= unsafe { raw::v8__Context__GetIsolate(&*context) }
{
panic!(
"{} and Context do not belong to the same Isolate",
type_name::<P>()
)
}
let new_scope_data = scope_data.new_context_scope_data(context);
new_scope_data.as_scope()
}
}
/// A stack-allocated class that governs a number of local handles.
/// After a handle scope has been created, all local handles will be
/// allocated within that handle scope until either the handle scope is
/// deleted or another handle scope is created. If there is already a
/// handle scope and a new one is created, all allocations will take
/// place in the new handle scope until it is deleted. After that,
/// new handles will again be allocated in the original handle scope.
///
/// After the handle scope of a local handle has been deleted the
/// garbage collector will no longer track the object stored in the
/// handle and may deallocate it. The behavior of accessing a handle
/// for which the handle scope has been deleted is undefined.
#[derive(Debug)]
pub struct HandleScope<'s, C = Context> {
_data: NonNull<data::ScopeData>,
_phantom: PhantomData<&'s mut C>,
}
impl<'s> HandleScope<'s> {
#[allow(clippy::new_ret_no_self)]
pub fn new<P: param::NewHandleScope<'s>>(param: &'s mut P) -> P::NewScope {
param
.get_scope_data_mut()
.new_handle_scope_data()
.as_scope()
}
/// Opens a new `HandleScope` and enters a `Context` in one step.
/// The first argument should be an `Isolate` or `OwnedIsolate`.
/// The second argument can be any handle that refers to a `Context` object;
/// usually this will be a `Global<Context>`.
pub fn with_context<
P: param::NewHandleScopeWithContext<'s>,
H: Handle<Data = Context>,
>(
param: &'s mut P,
context: H,
) -> Self {
let context_ref = context.open(param.get_isolate_mut());
param
.get_scope_data_mut()
.new_handle_scope_data_with_context(context_ref)
.as_scope()
}
/// Returns the context of the currently running JavaScript, or the context
/// on the top of the stack if no JavaScript is running.
pub fn get_current_context(&self) -> Local<'s, Context> {
let context_ptr = data::ScopeData::get(self).get_current_context();
unsafe { Local::from_raw(context_ptr) }.unwrap()
}
/// Returns either the last context entered through V8's C++ API, or the
/// context of the currently running microtask while processing microtasks.
/// If a context is entered while executing a microtask, that context is
/// returned.
pub fn get_entered_or_microtask_context(&self) -> Local<'s, Context> {
let data = data::ScopeData::get(self);
let isolate_ptr = data.get_isolate_ptr();
let context_ptr =
unsafe { raw::v8__Isolate__GetEnteredOrMicrotaskContext(isolate_ptr) };
unsafe { Local::from_raw(context_ptr) }.unwrap()
}
}
impl<'s> HandleScope<'s, ()> {
/// Schedules an exception to be thrown when returning to JavaScript. When
/// an exception has been scheduled it is illegal to invoke any
/// JavaScript operation; the caller must return immediately and only
/// after the exception has been handled does it become legal to invoke
/// JavaScript operations.
///
/// This function always returns the `undefined` value.
pub fn throw_exception(
&mut self,
exception: Local<Value>,
) -> Local<'s, Value> {
unsafe {
self.cast_local(|sd| {
raw::v8__Isolate__ThrowException(sd.get_isolate_ptr(), &*exception)
})
}
.unwrap()
}
pub(crate) unsafe fn cast_local<T>(
&mut self,
f: impl FnOnce(&mut data::ScopeData) -> *const T,
) -> Option<Local<'s, T>> {
Local::from_raw(f(data::ScopeData::get_mut(self)))
}
pub(crate) fn get_isolate_ptr(&self) -> *mut Isolate {
data::ScopeData::get(self).get_isolate_ptr()
}
}
impl<'s> HandleScope<'s> {
/// Return data that was previously attached to the isolate snapshot via
/// SnapshotCreator, and removes the reference to it. If called again with
/// same `index` argument, this function returns `DataError::NoData`.
///
/// The value that was stored in the snapshot must either match or be
/// convertible to type parameter `T`, otherwise `DataError::BadType` is
/// returned.
pub fn get_isolate_data_from_snapshot_once<T>(
&mut self,
index: usize,
) -> Result<Local<'s, T>, DataError>
where
T: 'static,
for<'l> Local<'l, Data>: TryInto<Local<'l, T>, Error = DataError>,
{
unsafe {
self
.cast_local(|sd| {
raw::v8__Isolate__GetDataFromSnapshotOnce(sd.get_isolate_ptr(), index)
})
.ok_or_else(DataError::no_data::<T>)
.and_then(|data| data.try_into())
}
}
/// Return data that was previously attached to the context snapshot via
/// SnapshotCreator, and removes the reference to it. If called again with
/// same `index` argument, this function returns `DataError::NoData`.
///
/// The value that was stored in the snapshot must either match or be
/// convertible to type parameter `T`, otherwise `DataError::BadType` is
/// returned.
pub fn get_context_data_from_snapshot_once<T>(
&mut self,
index: usize,
) -> Result<Local<'s, T>, DataError>
where
T: 'static,
for<'l> Local<'l, Data>: TryInto<Local<'l, T>, Error = DataError>,
{
unsafe {
self
.cast_local(|sd| {
raw::v8__Context__GetDataFromSnapshotOnce(
sd.get_current_context(),
index,
)
})
.ok_or_else(DataError::no_data::<T>)
.and_then(|data| data.try_into())
}
}
}
/// A HandleScope which first allocates a handle in the current scope
/// which will be later filled with the escape value.
// TODO(piscisaureus): type parameter `C` is not very useful in practice; being
// a source of complexity and potential confusion, it is desirable to
// eventually remove it. Blocker at the time of writing is that there are some
// tests that enter an `EscapableHandleScope` without creating a `ContextScope`
// at all. These tests need to updated first.
#[derive(Debug)]
pub struct EscapableHandleScope<'s, 'e: 's, C = Context> {
_data: NonNull<data::ScopeData>,
_phantom:
PhantomData<(&'s mut raw::HandleScope, &'e mut raw::EscapeSlot, &'s C)>,
}
impl<'s, 'e: 's> EscapableHandleScope<'s, 'e> {
#[allow(clippy::new_ret_no_self)]
pub fn new<P: param::NewEscapableHandleScope<'s, 'e>>(
param: &'s mut P,
) -> P::NewScope {
param
.get_scope_data_mut()
.new_escapable_handle_scope_data()
.as_scope()
}
}
impl<'s, 'e: 's, C> EscapableHandleScope<'s, 'e, C> {
/// Pushes the value into the previous scope and returns a handle to it.
/// Cannot be called twice.
pub fn escape<T>(&mut self, value: Local<T>) -> Local<'e, T>
where
for<'l> Local<'l, T>: Into<Local<'l, Data>>,
{
let escape_slot = data::ScopeData::get_mut(self)
.get_escape_slot_mut()
.expect("internal error: EscapableHandleScope has no escape slot")
.take()
.expect("EscapableHandleScope::escape() called twice");
escape_slot.escape(value)
}
}
/// An external exception handler.
#[derive(Debug)]
pub struct TryCatch<'s, P> {
_data: NonNull<data::ScopeData>,
_phantom: PhantomData<&'s mut P>,
}
impl<'s, P: param::NewTryCatch<'s>> TryCatch<'s, P> {
#[allow(clippy::new_ret_no_self)]
pub fn new(param: &'s mut P) -> P::NewScope {
param.get_scope_data_mut().new_try_catch_data().as_scope()
}
}
impl<'s, P> TryCatch<'s, P> {
/// Returns true if an exception has been caught by this try/catch block.
pub fn has_caught(&self) -> bool {
unsafe { raw::v8__TryCatch__HasCaught(self.get_raw()) }
}
/// For certain types of exceptions, it makes no sense to continue execution.
///
/// If CanContinue returns false, the correct action is to perform any C++
/// cleanup needed and then return. If CanContinue returns false and
/// HasTerminated returns true, it is possible to call
/// CancelTerminateExecution in order to continue calling into the engine.
pub fn can_continue(&self) -> bool {
unsafe { raw::v8__TryCatch__CanContinue(self.get_raw()) }
}
/// Returns true if an exception has been caught due to script execution
/// being terminated.
///
/// There is no JavaScript representation of an execution termination
/// exception. Such exceptions are thrown when the TerminateExecution
/// methods are called to terminate a long-running script.
///
/// If such an exception has been thrown, HasTerminated will return true,
/// indicating that it is possible to call CancelTerminateExecution in order
/// to continue calling into the engine.
pub fn has_terminated(&self) -> bool {
unsafe { raw::v8__TryCatch__HasTerminated(self.get_raw()) }
}
/// Returns true if verbosity is enabled.
pub fn is_verbose(&self) -> bool {
unsafe { raw::v8__TryCatch__IsVerbose(self.get_raw()) }
}
/// Set verbosity of the external exception handler.
///
/// By default, exceptions that are caught by an external exception
/// handler are not reported. Call SetVerbose with true on an
/// external exception handler to have exceptions caught by the
/// handler reported as if they were not caught.
pub fn set_verbose(&mut self, value: bool) {
unsafe { raw::v8__TryCatch__SetVerbose(self.get_raw_mut(), value) };
}
/// Set whether or not this TryCatch should capture a Message object
/// which holds source information about where the exception
/// occurred. True by default.
pub fn set_capture_message(&mut self, value: bool) {
unsafe { raw::v8__TryCatch__SetCaptureMessage(self.get_raw_mut(), value) };
}
/// Clears any exceptions that may have been caught by this try/catch block.
/// After this method has been called, HasCaught() will return false. Cancels
/// the scheduled exception if it is caught and ReThrow() is not called
/// before.
///
/// It is not necessary to clear a try/catch block before using it again; if
/// another exception is thrown the previously caught exception will just be
/// overwritten. However, it is often a good idea since it makes it easier
/// to determine which operation threw a given exception.
pub fn reset(&mut self) {
unsafe { raw::v8__TryCatch__Reset(self.get_raw_mut()) };
}
fn get_raw(&self) -> &raw::TryCatch {
data::ScopeData::get(self).get_try_catch()
}
fn get_raw_mut(&mut self) -> &mut raw::TryCatch {
data::ScopeData::get_mut(self).get_try_catch_mut()
}
}
impl<'s, 'p: 's, P> TryCatch<'s, P>
where
Self: AsMut<HandleScope<'p, ()>>,
{
/// Returns the exception caught by this try/catch block. If no exception has
/// been caught an empty handle is returned.
///
/// Note: v8.h states that "the returned handle is valid until this TryCatch
/// block has been destroyed". This is incorrect; the return value lives
/// no longer and no shorter than the active HandleScope at the time this
/// method is called. An issue has been opened about this in the V8 bug
/// tracker: https://bugs.chromium.org/p/v8/issues/detail?id=10537.
pub fn exception(&mut self) -> Option<Local<'p, Value>> {
unsafe {
self
.as_mut()
.cast_local(|sd| raw::v8__TryCatch__Exception(sd.get_try_catch()))
}
}
/// Returns the message associated with this exception. If there is
/// no message associated an empty handle is returned.
///
/// Note: the remark about the lifetime for the `exception()` return value
/// applies here too.
pub fn message(&mut self) -> Option<Local<'p, Message>> {
unsafe {
self
.as_mut()
.cast_local(|sd| raw::v8__TryCatch__Message(sd.get_try_catch()))
}
}
/// Throws the exception caught by this TryCatch in a way that avoids
/// it being caught again by this same TryCatch. As with ThrowException
/// it is illegal to execute any JavaScript operations after calling
/// ReThrow; the caller must return immediately to where the exception
/// is caught.
///
/// This function returns the `undefined` value when successful, or `None` if
/// no exception was caught and therefore there was nothing to rethrow.
pub fn rethrow(&mut self) -> Option<Local<'_, Value>> {
unsafe {
self
.as_mut()
.cast_local(|sd| raw::v8__TryCatch__ReThrow(sd.get_try_catch_mut()))
}
}
}
impl<'s, 'p: 's, P> TryCatch<'s, P>
where
Self: AsMut<HandleScope<'p>>,
{
/// Returns the .stack property of the thrown object. If no .stack
/// property is present an empty handle is returned.
pub fn stack_trace(&mut self) -> Option<Local<'p, Value>> {
unsafe {
self.as_mut().cast_local(|sd| {
raw::v8__TryCatch__StackTrace(
sd.get_try_catch(),
sd.get_current_context(),
)
})
}
}
}
/// A `CallbackScope` can be used to bootstrap a `HandleScope` and
/// `ContextScope` inside a callback function that gets called by V8.
/// Bootstrapping a scope inside a callback is the only valid use case of this
/// type; using it in other places leads to undefined behavior, which is also
/// the reason `CallbackScope::new()` is marked as being an unsafe function.
///
/// For some callback types, rusty_v8 internally creates a scope and passes it
/// as an argument to to embedder callback. Eventually we intend to wrap all
/// callbacks in this fashion, so the embedder would never needs to construct
/// a CallbackScope.
///
/// A `CallbackScope<()>`, without context, can be created from:
/// - `&mut Isolate`
/// - `&mut OwnedIsolate`
///
/// A `CallbackScope`, with context, can be created from:
/// - `Local<Context>`
/// - `Local<Message>`
/// - `Local<Object>`
/// - `Local<Promise>`
/// - `Local<SharedArrayBuffer>`
/// - `&FunctionCallbackInfo`
/// - `&PropertyCallbackInfo`
/// - `&PromiseRejectMessage`
#[derive(Debug)]
pub struct CallbackScope<'s, C = Context> {
_data: NonNull<data::ScopeData>,
_phantom: PhantomData<&'s mut HandleScope<'s, C>>,
}
impl<'s> CallbackScope<'s> {
#[allow(clippy::new_ret_no_self)]
pub unsafe fn new<P: param::NewCallbackScope<'s>>(param: P) -> P::NewScope {
let (isolate, context) = param.get_isolate_mut_and_maybe_current_context();
data::ScopeData::get_current_mut(isolate)
.new_callback_scope_data(context)
.as_scope()
}
}
macro_rules! impl_as {
// Implements `AsRef<Isolate>` and AsMut<Isolate>` on a scope type.
(<$($params:tt),+> $src_type:ty as Isolate) => {
impl<$($params),*> AsRef<Isolate> for $src_type {
fn as_ref(&self) -> &Isolate {
data::ScopeData::get(self).get_isolate()
}
}
impl<$($params),*> AsMut<Isolate> for $src_type {
fn as_mut(&mut self) -> &mut Isolate {
data::ScopeData::get_mut(self).get_isolate_mut()
}
}
};
// Implements `AsRef` and `AsMut` traits for the purpose of converting a
// a scope reference to a scope reference with a different but compatible type.
(<$($params:tt),+> $src_type:ty as $tgt_type:ty) => {
impl<$($params),*> AsRef<$tgt_type> for $src_type {
fn as_ref(&self) -> &$tgt_type {
self.cast_ref()
}
}
impl<$($params),*> AsMut< $tgt_type> for $src_type {
fn as_mut(&mut self) -> &mut $tgt_type {
self.cast_mut()
}
}
};
}
impl_as!(<'s, 'p, P> ContextScope<'s, P> as Isolate);
impl_as!(<'s, C> HandleScope<'s, C> as Isolate);
impl_as!(<'s, 'e, C> EscapableHandleScope<'s, 'e, C> as Isolate);
impl_as!(<'s, P> TryCatch<'s, P> as Isolate);
impl_as!(<'s, C> CallbackScope<'s, C> as Isolate);
impl_as!(<'s, 'p> ContextScope<'s, HandleScope<'p>> as HandleScope<'p, ()>);
impl_as!(<'s, 'p, 'e> ContextScope<'s, EscapableHandleScope<'p, 'e>> as HandleScope<'p, ()>);
impl_as!(<'s, C> HandleScope<'s, C> as HandleScope<'s, ()>);
impl_as!(<'s, 'e, C> EscapableHandleScope<'s, 'e, C> as HandleScope<'s, ()>);
impl_as!(<'s, 'p, C> TryCatch<'s, HandleScope<'p, C>> as HandleScope<'p, ()>);
impl_as!(<'s, 'p, 'e, C> TryCatch<'s, EscapableHandleScope<'p, 'e, C>> as HandleScope<'p, ()>);
impl_as!(<'s, C> CallbackScope<'s, C> as HandleScope<'s, ()>);
impl_as!(<'s, 'p> ContextScope<'s, HandleScope<'p>> as HandleScope<'p>);
impl_as!(<'s, 'p, 'e> ContextScope<'s, EscapableHandleScope<'p, 'e>> as HandleScope<'p>);
impl_as!(<'s> HandleScope<'s> as HandleScope<'s>);
impl_as!(<'s, 'e> EscapableHandleScope<'s, 'e> as HandleScope<'s>);
impl_as!(<'s, 'p> TryCatch<'s, HandleScope<'p>> as HandleScope<'p>);
impl_as!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e>> as HandleScope<'p>);
impl_as!(<'s> CallbackScope<'s> as HandleScope<'s>);
impl_as!(<'s, 'p, 'e> ContextScope<'s, EscapableHandleScope<'p, 'e>> as EscapableHandleScope<'p, 'e, ()>);
impl_as!(<'s, 'e, C> EscapableHandleScope<'s, 'e, C> as EscapableHandleScope<'s, 'e, ()>);
impl_as!(<'s, 'p, 'e, C> TryCatch<'s, EscapableHandleScope<'p, 'e, C>> as EscapableHandleScope<'p, 'e, ()>);
impl_as!(<'s, 'p, 'e> ContextScope<'s, EscapableHandleScope<'p, 'e>> as EscapableHandleScope<'p, 'e>);
impl_as!(<'s, 'e> EscapableHandleScope<'s, 'e> as EscapableHandleScope<'s, 'e>);
impl_as!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e>> as EscapableHandleScope<'p, 'e>);
impl_as!(<'s, 'p, C> TryCatch<'s, HandleScope<'p, C>> as TryCatch<'s, HandleScope<'p, ()>>);
impl_as!(<'s, 'p, 'e, C> TryCatch<'s, EscapableHandleScope<'p, 'e, C>> as TryCatch<'s, HandleScope<'p, ()>>);
impl_as!(<'s, 'p, 'e, C> TryCatch<'s, EscapableHandleScope<'p, 'e, C>> as TryCatch<'s, EscapableHandleScope<'p, 'e, ()>>);
impl_as!(<'s, 'p> TryCatch<'s, HandleScope<'p>> as TryCatch<'s, HandleScope<'p>>);
impl_as!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e>> as TryCatch<'s, HandleScope<'p>>);
impl_as!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e>> as TryCatch<'s, EscapableHandleScope<'p, 'e>>);
macro_rules! impl_deref {
(<$($params:tt),+> $src_type:ty as $tgt_type:ty) => {
impl<$($params),*> Deref for $src_type {
type Target = $tgt_type;
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl<$($params),*> DerefMut for $src_type {
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut()
}
}
};
}
impl_deref!(<'s, 'p> ContextScope<'s, HandleScope<'p>> as HandleScope<'p>);
impl_deref!(<'s, 'p, 'e> ContextScope<'s, EscapableHandleScope<'p, 'e>> as EscapableHandleScope<'p, 'e>);
impl_deref!(<'s> HandleScope<'s, ()> as Isolate);
impl_deref!(<'s> HandleScope<'s> as HandleScope<'s, ()>);
impl_deref!(<'s, 'e> EscapableHandleScope<'s, 'e, ()> as HandleScope<'s, ()>);
impl_deref!(<'s, 'e> EscapableHandleScope<'s, 'e> as HandleScope<'s>);
impl_deref!(<'s, 'p> TryCatch<'s, HandleScope<'p, ()>> as HandleScope<'p, ()>);
impl_deref!(<'s, 'p> TryCatch<'s, HandleScope<'p>> as HandleScope<'p>);
impl_deref!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e, ()>> as EscapableHandleScope<'p, 'e, ()>);
impl_deref!(<'s, 'p, 'e> TryCatch<'s, EscapableHandleScope<'p, 'e>> as EscapableHandleScope<'p, 'e>);
impl_deref!(<'s> CallbackScope<'s, ()> as HandleScope<'s, ()>);
impl_deref!(<'s> CallbackScope<'s> as HandleScope<'s>);
macro_rules! impl_scope_drop {
(<$($params:tt),+> $type:ty) => {
unsafe impl<$($params),*> Scope for $type {}
impl<$($params),*> Drop for $type {
fn drop(&mut self) {
data::ScopeData::get_mut(self).notify_scope_dropped();
}
}
};
}
impl_scope_drop!(<'s, 'p, P> ContextScope<'s, P>);
impl_scope_drop!(<'s, C> HandleScope<'s, C> );
impl_scope_drop!(<'s, 'e, C> EscapableHandleScope<'s, 'e, C> );
impl_scope_drop!(<'s, P> TryCatch<'s, P> );
impl_scope_drop!(<'s, C> CallbackScope<'s, C> );
pub unsafe trait Scope: Sized {}
trait ScopeCast: Sized {
fn cast_ref<S: Scope>(&self) -> &S;
fn cast_mut<S: Scope>(&mut self) -> &mut S;
}
impl<T: Scope> ScopeCast for T {
fn cast_ref<S: Scope>(&self) -> &S {
assert_eq!(Layout::new::<Self>(), Layout::new::<S>());
unsafe { &*(self as *const _ as *const S) }
}
fn cast_mut<S: Scope>(&mut self) -> &mut S {
assert_eq!(Layout::new::<Self>(), Layout::new::<S>());
unsafe { &mut *(self as *mut _ as *mut S) }
}
}
/// Scopes are typically constructed as the child of another scope. The scope
/// that is returned from `«Child»Scope::new(parent: &mut «Parent»Scope)` does
/// not necessarily have type `«Child»Scope`, but rather its type is a merger of
/// both the the parent and child scope types.
///
/// For example: a `ContextScope` created inside `HandleScope<'a, ()>` does not
/// produce a `ContextScope`, but rather a `HandleScope<'a, Context>`, which
/// describes a scope that is both a `HandleScope` _and_ a `ContextScope`.
///
/// The Traits in the (private) `param` module define which types can be passed
/// as a parameter to the `«Some»Scope::new()` constructor, and what the
/// actual, merged scope type will be that `new()` returns for a specific
/// parameter type.
mod param {
use super::*;
pub trait NewContextScope<'s>: getter::GetScopeData {
type NewScope: Scope;
}
impl<'s, 'p: 's, P: Scope> NewContextScope<'s> for ContextScope<'p, P> {
type NewScope = ContextScope<'s, P>;
}
impl<'s, 'p: 's, C> NewContextScope<'s> for HandleScope<'p, C> {
type NewScope = ContextScope<'s, HandleScope<'p>>;
}
impl<'s, 'p: 's, 'e: 'p, C> NewContextScope<'s>
for EscapableHandleScope<'p, 'e, C>
{
type NewScope = ContextScope<'s, EscapableHandleScope<'p, 'e>>;
}
impl<'s, 'p: 's, P: NewContextScope<'s>> NewContextScope<'s>
for TryCatch<'p, P>
{
type NewScope = <P as NewContextScope<'s>>::NewScope;
}
impl<'s, 'p: 's, C> NewContextScope<'s> for CallbackScope<'p, C> {
type NewScope = ContextScope<'s, HandleScope<'p>>;
}
pub trait NewHandleScope<'s>: getter::GetScopeData {
type NewScope: Scope;
}
impl<'s> NewHandleScope<'s> for Isolate {
type NewScope = HandleScope<'s, ()>;
}
impl<'s> NewHandleScope<'s> for OwnedIsolate {
type NewScope = HandleScope<'s, ()>;
}
impl<'s, 'p: 's, P: NewHandleScope<'s>> NewHandleScope<'s>
for ContextScope<'p, P>
{
type NewScope = <P as NewHandleScope<'s>>::NewScope;
}
impl<'s, 'p: 's, C> NewHandleScope<'s> for HandleScope<'p, C> {
type NewScope = HandleScope<'s, C>;
}
impl<'s, 'p: 's, 'e: 'p, C> NewHandleScope<'s>
for EscapableHandleScope<'p, 'e, C>
{
type NewScope = EscapableHandleScope<'s, 'e, C>;
}
impl<'s, 'p: 's, P: NewHandleScope<'s>> NewHandleScope<'s> for TryCatch<'p, P> {
type NewScope = <P as NewHandleScope<'s>>::NewScope;
}
impl<'s, 'p: 's, C> NewHandleScope<'s> for CallbackScope<'p, C> {
type NewScope = HandleScope<'s, C>;
}
pub trait NewHandleScopeWithContext<'s>: getter::GetScopeData {
fn get_isolate_mut(&mut self) -> &mut Isolate;
}
impl<'s> NewHandleScopeWithContext<'s> for Isolate {
fn get_isolate_mut(&mut self) -> &mut Isolate {
self
}
}
impl<'s> NewHandleScopeWithContext<'s> for OwnedIsolate {
fn get_isolate_mut(&mut self) -> &mut Isolate {
&mut *self
}
}
pub trait NewEscapableHandleScope<'s, 'e: 's>: getter::GetScopeData {
type NewScope: Scope;
}
impl<'s, 'p: 's, 'e: 'p, P: NewEscapableHandleScope<'s, 'e>>
NewEscapableHandleScope<'s, 'e> for ContextScope<'p, P>
{
type NewScope = <P as NewEscapableHandleScope<'s, 'e>>::NewScope;
}
impl<'s, 'p: 's, C> NewEscapableHandleScope<'s, 'p> for HandleScope<'p, C> {
type NewScope = EscapableHandleScope<'s, 'p, C>;
}
impl<'s, 'p: 's, 'e: 'p, C> NewEscapableHandleScope<'s, 'p>
for EscapableHandleScope<'p, 'e, C>
{
type NewScope = EscapableHandleScope<'s, 'p, C>;
}
impl<'s, 'p: 's, 'e: 'p, P: NewEscapableHandleScope<'s, 'e>>
NewEscapableHandleScope<'s, 'e> for TryCatch<'p, P>
{
type NewScope = <P as NewEscapableHandleScope<'s, 'e>>::NewScope;
}
impl<'s, 'p: 's, C> NewEscapableHandleScope<'s, 'p> for CallbackScope<'p, C> {
type NewScope = EscapableHandleScope<'s, 'p, C>;
}
pub trait NewTryCatch<'s>: getter::GetScopeData {
type NewScope: Scope;
}
impl<'s, 'p: 's, P: NewTryCatch<'s>> NewTryCatch<'s> for ContextScope<'p, P> {
type NewScope = <P as NewTryCatch<'s>>::NewScope;
}
impl<'s, 'p: 's, C> NewTryCatch<'s> for HandleScope<'p, C> {
type NewScope = TryCatch<'s, HandleScope<'p, C>>;
}
impl<'s, 'p: 's, 'e: 'p, C> NewTryCatch<'s>
for EscapableHandleScope<'p, 'e, C>
{
type NewScope = TryCatch<'s, EscapableHandleScope<'p, 'e, C>>;
}
impl<'s, 'p: 's, P> NewTryCatch<'s> for TryCatch<'p, P> {
type NewScope = TryCatch<'s, P>;
}
impl<'s, 'p: 's, C> NewTryCatch<'s> for CallbackScope<'p, C> {
type NewScope = TryCatch<'s, HandleScope<'p, C>>;
}
pub trait NewCallbackScope<'s>: Sized + getter::GetIsolate<'s> {
type NewScope: Scope;
unsafe fn get_isolate_mut_and_maybe_current_context(
self,
) -> (&'s mut Isolate, Option<Local<'s, Context>>) {
(self.get_isolate_mut(), None)
}
}
impl<'s> NewCallbackScope<'s> for &'s mut Isolate {
type NewScope = CallbackScope<'s, ()>;
}
impl<'s> NewCallbackScope<'s> for &'s mut OwnedIsolate {
type NewScope = CallbackScope<'s, ()>;
}
impl<'s> NewCallbackScope<'s> for &'s FunctionCallbackInfo {
type NewScope = CallbackScope<'s>;
}
impl<'s> NewCallbackScope<'s> for &'s PropertyCallbackInfo {
type NewScope = CallbackScope<'s>;
}
impl<'s> NewCallbackScope<'s> for Local<'s, Context> {
type NewScope = CallbackScope<'s>;
unsafe fn get_isolate_mut_and_maybe_current_context(
self,
) -> (&'s mut Isolate, Option<Local<'s, Context>>) {
(getter::GetIsolate::get_isolate_mut(self), Some(self))
}
}
impl<'s> NewCallbackScope<'s> for Local<'s, Message> {
type NewScope = CallbackScope<'s>;
}
impl<'s, T: Into<Local<'s, Object>>> NewCallbackScope<'s> for T {
type NewScope = CallbackScope<'s>;
}
impl<'s> NewCallbackScope<'s> for &'s PromiseRejectMessage<'s> {
type NewScope = CallbackScope<'s>;
}
}
/// The private `getter` module defines traits to look up the related `Isolate`
/// and `ScopeData` for many different types. The implementation of those traits
/// on the types that implement them are also all contained in this module.
mod getter {
pub use super::*;
pub trait GetIsolate<'s> {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate;
}
impl<'s> GetIsolate<'s> for &'s mut Isolate {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
self
}
}
impl<'s> GetIsolate<'s> for &'s mut OwnedIsolate {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
&mut *self
}
}
impl<'s> GetIsolate<'s> for &'s FunctionCallbackInfo {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
&mut *raw::v8__FunctionCallbackInfo__GetIsolate(self)
}
}
impl<'s> GetIsolate<'s> for &'s PropertyCallbackInfo {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
&mut *raw::v8__PropertyCallbackInfo__GetIsolate(self)
}
}
impl<'s> GetIsolate<'s> for Local<'s, Context> {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
&mut *raw::v8__Context__GetIsolate(&*self)
}
}
impl<'s> GetIsolate<'s> for Local<'s, Message> {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
&mut *raw::v8__Message__GetIsolate(&*self)
}
}
impl<'s, T: Into<Local<'s, Object>>> GetIsolate<'s> for T {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
let object: Local<Object> = self.into();
&mut *raw::v8__Object__GetIsolate(&*object)
}
}
impl<'s> GetIsolate<'s> for &'s PromiseRejectMessage<'s> {
unsafe fn get_isolate_mut(self) -> &'s mut Isolate {
let object: Local<Object> = self.get_promise().into();
&mut *raw::v8__Object__GetIsolate(&*object)
}
}
pub trait GetScopeData {
fn get_scope_data_mut(&mut self) -> &mut data::ScopeData;
}
impl<T: Scope> GetScopeData for T {
fn get_scope_data_mut(&mut self) -> &mut data::ScopeData {
data::ScopeData::get_mut(self)
}
}
impl GetScopeData for Isolate {
fn get_scope_data_mut(&mut self) -> &mut data::ScopeData {
data::ScopeData::get_root_mut(self)
}
}
impl GetScopeData for OwnedIsolate {
fn get_scope_data_mut(&mut self) -> &mut data::ScopeData {
data::ScopeData::get_root_mut(self)
}
}
}
/// All publicly exported `«Some»Scope` types are essentially wrapping a pointer
/// to a heap-allocated struct `ScopeData`. This module contains the definition
/// for `ScopeData` and its inner types, as well as related helper traits.
pub(crate) mod data {
use super::*;
#[derive(Debug)]
pub struct ScopeData {
// The first four fields are always valid - even when the `Box<ScopeData>`
// struct is free (does not contain data related to an actual scope).
// The `previous` and `isolate` fields never change; the `next` field is
// set to `None` initially when the struct is created, but it may later be
// assigned a `Some(Box<ScopeData>)` value, after which this field never
// changes again.
isolate: NonNull<Isolate>,
previous: Option<NonNull<ScopeData>>,
next: Option<Box<ScopeData>>,
// The 'status' field is also always valid (but does change).
status: Cell<ScopeStatus>,
// The following fields are only valid when this ScopeData object is in use
// (eiter current or shadowed -- not free).
context: Cell<Option<NonNull<Context>>>,
escape_slot: Option<NonNull<Option<raw::EscapeSlot>>>,
try_catch: Option<NonNull<raw::TryCatch>>,
scope_type_specific_data: ScopeTypeSpecificData,
}
impl ScopeData {
/// Returns a mutable reference to the data associated with topmost scope
/// on the scope stack. This function does not automatically exit zombie
/// scopes, so it might return a zombie ScopeData reference.
pub(crate) fn get_current_mut(isolate: &mut Isolate) -> &mut Self {
let self_mut = isolate
.get_current_scope_data()
.map(NonNull::as_ptr)
.map(|p| unsafe { &mut *p })
.unwrap();
match self_mut.status.get() {
ScopeStatus::Current { .. } => self_mut,
_ => unreachable!(),
}
}
/// Initializes the scope stack by creating a 'dummy' `ScopeData` at the
/// very bottom. This makes it possible to store the freelist of reusable
/// ScopeData objects even when no scope is entered.
pub(crate) fn new_root(isolate: &mut Isolate) {
let root = Box::leak(Self::boxed(isolate.into()));
root.status = ScopeStatus::Current { zombie: false }.into();
debug_assert!(isolate.get_current_scope_data().is_none());