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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
/* 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 http://mozilla.org/MPL/2.0/. */

//! Rust wrappers around the raw JS apis

use std::cell::Cell;
use std::char;
use std::default::Default;
use std::ffi;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::slice;
use std::str;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, RwLock};

use crate::consts::{JSCLASS_GLOBAL_SLOT_COUNT, JSCLASS_RESERVED_SLOTS_MASK};
use crate::consts::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL};
use crate::conversions::jsstr_to_string;
use crate::default_heapsize;
pub use crate::gc::Traceable as Trace;
pub use crate::gc::*;
use crate::glue::AppendToRootedObjectVector;
use crate::glue::{CreateRootedIdVector, CreateRootedObjectVector};
use crate::glue::{
    DeleteCompileOptions, DeleteRootedObjectVector, DescribeScriptedCaller, DestroyRootedIdVector,
};
use crate::glue::{
    GetIdVectorAddress, GetObjectVectorAddress, NewCompileOptions, SliceRootedIdVector,
};
use crate::jsapi;
use crate::jsapi::glue::{DeleteRealmOptions, JS_Init, JS_NewRealmOptions};
use crate::jsapi::js::frontend::CompilationStencil;
use crate::jsapi::mozilla::Utf8Unit;
use crate::jsapi::shadow::BaseShape;
use crate::jsapi::HandleObjectVector as RawHandleObjectVector;
use crate::jsapi::HandleValue as RawHandleValue;
use crate::jsapi::JS_AddExtraGCRootsTracer;
use crate::jsapi::MutableHandleIdVector as RawMutableHandleIdVector;
use crate::jsapi::{already_AddRefed, jsid};
use crate::jsapi::{BuildStackString, CaptureCurrentStack, StackFormat};
use crate::jsapi::{Evaluate2, HandleValueArray, StencilRelease};
use crate::jsapi::{InitSelfHostedCode, IsWindowSlow};
use crate::jsapi::{
    JSAutoRealm, JS_SetGCParameter, JS_SetNativeStackQuota, JS_WrapObject, JS_WrapValue,
};
use crate::jsapi::{JSClass, JSClassOps, JSContext, Realm, JSCLASS_RESERVED_SLOTS_SHIFT};
use crate::jsapi::{JSErrorReport, JSFunctionSpec, JSGCParamKey};
use crate::jsapi::{JSObject, JSPropertySpec, JSRuntime};
use crate::jsapi::{JSString, Object, PersistentRootedIdVector};
use crate::jsapi::{JS_DefineFunctions, JS_DefineProperties, JS_DestroyContext, JS_ShutDown};
use crate::jsapi::{JS_EnumerateStandardClasses, JS_GetRuntime, JS_GlobalObjectTraceHook};
use crate::jsapi::{JS_MayResolveStandardClass, JS_NewContext, JS_ResolveStandardClass};
use crate::jsapi::{JS_RequestInterruptCallback, JS_RequestInterruptCallbackCanWait};
use crate::jsapi::{JS_StackCapture_AllFrames, JS_StackCapture_MaxFrames};
use crate::jsapi::{PersistentRootedObjectVector, ReadOnlyCompileOptions, RootingContext};
use crate::jsapi::{SetWarningReporter, SourceText, ToBooleanSlow};
use crate::jsapi::{ToInt32Slow, ToInt64Slow, ToNumberSlow, ToStringSlow, ToUint16Slow};
use crate::jsapi::{ToUint32Slow, ToUint64Slow, ToWindowProxyIfWindowSlow};
use crate::jsval::ObjectValue;
use crate::panic::maybe_resume_unwind;
use lazy_static::lazy_static;
use log::{debug, warn};
pub use mozjs_sys::jsgc::{GCMethods, IntoHandle, IntoMutableHandle};

use crate::rooted;

// From Gecko:
// Our "default" stack is what we use in configurations where we don't have a compelling reason to
// do things differently. This is effectively 1MB on 64-bit platforms.
const STACK_QUOTA: usize = 128 * 8 * 1024;

// From Gecko:
// The JS engine permits us to set different stack limits for system code,
// trusted script, and untrusted script. We have tests that ensure that
// we can always execute 10 "heavy" (eval+with) stack frames deeper in
// privileged code. Our stack sizes vary greatly in different configurations,
// so satisfying those tests requires some care. Manual measurements of the
// number of heavy stack frames achievable gives us the following rough data,
// ordered by the effective categories in which they are grouped in the
// JS_SetNativeStackQuota call (which predates this analysis).
//
// (NB: These numbers may have drifted recently - see bug 938429)
// OSX 64-bit Debug: 7MB stack, 636 stack frames => ~11.3k per stack frame
// OSX64 Opt: 7MB stack, 2440 stack frames => ~3k per stack frame
//
// Linux 32-bit Debug: 2MB stack, 426 stack frames => ~4.8k per stack frame
// Linux 64-bit Debug: 4MB stack, 455 stack frames => ~9.0k per stack frame
//
// Windows (Opt+Debug): 900K stack, 235 stack frames => ~3.4k per stack frame
//
// Linux 32-bit Opt: 1MB stack, 272 stack frames => ~3.8k per stack frame
// Linux 64-bit Opt: 2MB stack, 316 stack frames => ~6.5k per stack frame
//
// We tune the trusted/untrusted quotas for each configuration to achieve our
// invariants while attempting to minimize overhead. In contrast, our buffer
// between system code and trusted script is a very unscientific 10k.
const SYSTEM_CODE_BUFFER: usize = 10 * 1024;

// Gecko's value on 64-bit.
const TRUSTED_SCRIPT_BUFFER: usize = 8 * 12800;

trait ToResult {
    fn to_result(self) -> Result<(), ()>;
}

impl ToResult for bool {
    fn to_result(self) -> Result<(), ()> {
        if self {
            Ok(())
        } else {
            Err(())
        }
    }
}

// ___________________________________________________________________________
// friendly Rustic API to runtimes

pub struct RealmOptions(*mut jsapi::RealmOptions);

impl Deref for RealmOptions {
    type Target = jsapi::RealmOptions;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.0 }
    }
}

impl DerefMut for RealmOptions {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.0 }
    }
}

impl Default for RealmOptions {
    fn default() -> RealmOptions {
        RealmOptions(unsafe { JS_NewRealmOptions() })
    }
}

impl Drop for RealmOptions {
    fn drop(&mut self) {
        unsafe { DeleteRealmOptions(self.0) }
    }
}

thread_local!(static CONTEXT: Cell<*mut JSContext> = Cell::new(ptr::null_mut()));

#[derive(PartialEq)]
enum EngineState {
    Uninitialized,
    InitFailed,
    Initialized,
    ShutDown,
}

lazy_static! {
    static ref ENGINE_STATE: Mutex<EngineState> = Mutex::new(EngineState::Uninitialized);
}

#[derive(Debug)]
pub enum JSEngineError {
    AlreadyInitialized,
    AlreadyShutDown,
    InitFailed,
}

/// A handle that must be kept alive in order to create new Runtimes.
/// When this handle is dropped, the engine is shut down and cannot
/// be reinitialized.
pub struct JSEngine {
    /// The count of alive handles derived from this initialized instance.
    outstanding_handles: Arc<AtomicU32>,
    // Ensure this type cannot be sent between threads.
    marker: PhantomData<*mut ()>,
}

pub struct JSEngineHandle(Arc<AtomicU32>);

impl Clone for JSEngineHandle {
    fn clone(&self) -> JSEngineHandle {
        self.0.fetch_add(1, Ordering::SeqCst);
        JSEngineHandle(self.0.clone())
    }
}

impl Drop for JSEngineHandle {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

impl JSEngine {
    /// Initialize the JS engine to prepare for creating new JS runtimes.
    pub fn init() -> Result<JSEngine, JSEngineError> {
        let mut state = ENGINE_STATE.lock().unwrap();
        match *state {
            EngineState::Initialized => return Err(JSEngineError::AlreadyInitialized),
            EngineState::InitFailed => return Err(JSEngineError::InitFailed),
            EngineState::ShutDown => return Err(JSEngineError::AlreadyShutDown),
            EngineState::Uninitialized => (),
        }
        if unsafe { !JS_Init() } {
            *state = EngineState::InitFailed;
            Err(JSEngineError::InitFailed)
        } else {
            *state = EngineState::Initialized;
            Ok(JSEngine {
                outstanding_handles: Arc::new(AtomicU32::new(0)),
                marker: PhantomData,
            })
        }
    }

    pub fn can_shutdown(&self) -> bool {
        self.outstanding_handles.load(Ordering::SeqCst) == 0
    }

    /// Create a handle to this engine.
    pub fn handle(&self) -> JSEngineHandle {
        self.outstanding_handles.fetch_add(1, Ordering::SeqCst);
        JSEngineHandle(self.outstanding_handles.clone())
    }
}

/// Shut down the JS engine, invalidating any existing runtimes and preventing
/// any new ones from being created.
impl Drop for JSEngine {
    fn drop(&mut self) {
        let mut state = ENGINE_STATE.lock().unwrap();
        if *state == EngineState::Initialized {
            assert_eq!(
                self.outstanding_handles.load(Ordering::SeqCst),
                0,
                "There are outstanding JS engine handles"
            );
            *state = EngineState::ShutDown;
            unsafe {
                JS_ShutDown();
            }
        }
    }
}

pub fn transform_str_to_source_text(source: &str) -> SourceText<Utf8Unit> {
    SourceText {
        units_: source.as_ptr() as *const _,
        length_: source.len() as u32,
        ownsUnits_: false,
        _phantom_0: PhantomData,
    }
}

pub fn transform_u16_to_source_text(source: &[u16]) -> SourceText<u16> {
    SourceText {
        units_: source.as_ptr() as *const _,
        length_: source.len() as u32,
        ownsUnits_: false,
        _phantom_0: PhantomData,
    }
}

/// A handle to a Runtime that will be used to create a new runtime in another
/// thread. This handle and the new runtime must be destroyed before the original
/// runtime can be dropped.
pub struct ParentRuntime {
    /// Raw pointer to the underlying SpiderMonkey runtime.
    parent: *mut JSRuntime,
    /// Handle to ensure the JS engine remains running while this handle exists.
    engine: JSEngineHandle,
    /// The number of children of the runtime that created this ParentRuntime value.
    children_of_parent: Arc<()>,
}
unsafe impl Send for ParentRuntime {}

/// A wrapper for the `JSContext` structure in SpiderMonkey.
pub struct Runtime {
    /// Raw pointer to the underlying SpiderMonkey context.
    cx: *mut JSContext,
    /// The engine that this runtime is associated with.
    engine: JSEngineHandle,
    /// If this Runtime was created with a parent, this member exists to ensure
    /// that that parent's count of outstanding children (see [outstanding_children])
    /// remains accurate and will be automatically decreased when this Runtime value
    /// is dropped.
    _parent_child_count: Option<Arc<()>>,
    /// The strong references to this value represent the number of child runtimes
    /// that have been created using this Runtime as a parent. Since Runtime values
    /// must be associated with a particular thread, we cannot simply use Arc<Runtime>
    /// to represent the resulting ownership graph and risk destroying a Runtime on
    /// the wrong thread.
    outstanding_children: Arc<()>,
    /// An `Option` that holds the same pointer as `cx`.
    /// This is shared with all [`ThreadSafeJSContext`]s, so
    /// they can detect when it's destroyed on the main thread.
    thread_safe_handle: Arc<RwLock<Option<*mut JSContext>>>,
}

impl Runtime {
    /// Get the `JSContext` for this thread.
    pub fn get() -> *mut JSContext {
        let cx = CONTEXT.with(|context| context.get());
        assert!(!cx.is_null());
        cx
    }

    /// Create a [`ThreadSafeJSContext`] that can detect when this `Runtime` is destroyed.
    pub fn thread_safe_js_context(&self) -> ThreadSafeJSContext {
        ThreadSafeJSContext(self.thread_safe_handle.clone())
    }

    /// Creates a new `JSContext`.
    pub fn new(engine: JSEngineHandle) -> Runtime {
        unsafe { Self::create(engine, None) }
    }

    /// Signal that a new child runtime will be created in the future, and ensure
    /// that this runtime will not allow itself to be destroyed before the new
    /// child runtime. Returns a handle that can be passed to `create_with_parent`
    /// in order to create a new runtime on another thread that is associated with
    /// this runtime.
    pub fn prepare_for_new_child(&self) -> ParentRuntime {
        ParentRuntime {
            parent: self.rt(),
            engine: self.engine.clone(),
            children_of_parent: self.outstanding_children.clone(),
        }
    }

    /// Creates a new `JSContext` with a parent runtime. If the parent does not outlive
    /// the new runtime, its destructor will assert.
    ///
    /// Unsafety:
    /// If panicking does not abort the program, any threads with child runtimes will
    /// continue executing after the thread with the parent runtime panics, but they
    /// will be in an invalid and undefined state.
    pub unsafe fn create_with_parent(parent: ParentRuntime) -> Runtime {
        Self::create(parent.engine.clone(), Some(parent))
    }

    unsafe fn create(engine: JSEngineHandle, parent: Option<ParentRuntime>) -> Runtime {
        let parent_runtime = parent.as_ref().map_or(ptr::null_mut(), |r| r.parent);
        let js_context = JS_NewContext(default_heapsize + (ChunkSize as u32), parent_runtime);
        assert!(!js_context.is_null());

        // Unconstrain the runtime's threshold on nominal heap size, to avoid
        // triggering GC too often if operating continuously near an arbitrary
        // finite threshold. This leaves the maximum-JS_malloc-bytes threshold
        // still in effect to cause periodical, and we hope hygienic,
        // last-ditch GCs from within the GC's allocator.
        JS_SetGCParameter(js_context, JSGCParamKey::JSGC_MAX_BYTES, u32::MAX);

        JS_AddExtraGCRootsTracer(js_context, Some(trace_traceables), ptr::null_mut());

        JS_SetNativeStackQuota(
            js_context,
            STACK_QUOTA,
            STACK_QUOTA - SYSTEM_CODE_BUFFER,
            STACK_QUOTA - SYSTEM_CODE_BUFFER - TRUSTED_SCRIPT_BUFFER,
        );

        CONTEXT.with(|context| {
            assert!(context.get().is_null());
            context.set(js_context);
        });

        #[cfg(target_pointer_width = "64")]
        InitSelfHostedCode(js_context, [0u64; 2], None);
        #[cfg(target_pointer_width = "32")]
        InitSelfHostedCode(js_context, [0u32; 2], None);

        SetWarningReporter(js_context, Some(report_warning));

        Runtime {
            engine,
            _parent_child_count: parent.map(|p| p.children_of_parent),
            cx: js_context,
            outstanding_children: Arc::new(()),
            thread_safe_handle: Arc::new(RwLock::new(Some(js_context))),
        }
    }

    /// Returns the `JSRuntime` object.
    pub fn rt(&self) -> *mut JSRuntime {
        unsafe { JS_GetRuntime(self.cx) }
    }

    /// Returns the `JSContext` object.
    pub fn cx(&self) -> *mut JSContext {
        self.cx
    }

    pub fn evaluate_script(
        &self,
        glob: HandleObject,
        script: &str,
        filename: &str,
        line_num: u32,
        rval: MutableHandleValue,
    ) -> Result<(), ()> {
        debug!(
            "Evaluating script from {} with content {}",
            filename, script
        );

        let _ac = JSAutoRealm::new(self.cx(), glob.get());
        let options = unsafe { CompileOptionsWrapper::new(self.cx(), filename, line_num) };

        unsafe {
            let mut source = transform_str_to_source_text(&script);
            if !Evaluate2(self.cx(), options.ptr, &mut source, rval.into()) {
                debug!("...err!");
                maybe_resume_unwind();
                Err(())
            } else {
                // we could return the script result but then we'd have
                // to root it and so forth and, really, who cares?
                debug!("...ok!");
                Ok(())
            }
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        self.thread_safe_handle.write().unwrap().take();
        assert_eq!(
            Arc::strong_count(&self.outstanding_children),
            1,
            "This runtime still has live children."
        );
        unsafe {
            JS_DestroyContext(self.cx);

            CONTEXT.with(|context| {
                assert_eq!(context.get(), self.cx);
                context.set(ptr::null_mut());
            });
        }
    }
}

/// A version of the [`JSContext`] that can be used from other threads and is thus
/// `Send` and `Sync`. This should only ever expose operations that are marked as
/// thread-safe by the SpiderMonkey API, ie ones that only atomic fields in JSContext.
#[derive(Clone)]
pub struct ThreadSafeJSContext(Arc<RwLock<Option<*mut JSContext>>>);

unsafe impl Send for ThreadSafeJSContext {}
unsafe impl Sync for ThreadSafeJSContext {}

impl ThreadSafeJSContext {
    /// Call `JS_RequestInterruptCallback` from the SpiderMonkey API.
    /// This is thread-safe according to
    /// <https://searchfox.org/mozilla-central/rev/7a85a111b5f42cdc07f438e36f9597c4c6dc1d48/js/public/Interrupt.h#19>
    pub fn request_interrupt_callback(&self) {
        if let Some(&cx) = self.0.read().unwrap().as_ref() {
            unsafe {
                JS_RequestInterruptCallback(cx);
            }
        }
    }

    /// Call `JS_RequestInterruptCallbackCanWait` from the SpiderMonkey API.
    /// This is thread-safe according to
    /// <https://searchfox.org/mozilla-central/rev/7a85a111b5f42cdc07f438e36f9597c4c6dc1d48/js/public/Interrupt.h#19>
    pub fn request_interrupt_callback_can_wait(&self) {
        if let Some(&cx) = self.0.read().unwrap().as_ref() {
            unsafe {
                JS_RequestInterruptCallbackCanWait(cx);
            }
        }
    }
}

const ChunkShift: usize = 20;
const ChunkSize: usize = 1 << ChunkShift;

#[cfg(target_pointer_width = "32")]
const ChunkLocationOffset: usize = ChunkSize - 2 * 4 - 8;

// ___________________________________________________________________________
// Wrappers around things in jsglue.cpp

pub struct RootedObjectVectorWrapper {
    pub ptr: *mut PersistentRootedObjectVector,
}

impl RootedObjectVectorWrapper {
    pub fn new(cx: *mut JSContext) -> RootedObjectVectorWrapper {
        RootedObjectVectorWrapper {
            ptr: unsafe { CreateRootedObjectVector(cx) },
        }
    }

    pub fn append(&self, obj: *mut JSObject) -> bool {
        unsafe { AppendToRootedObjectVector(self.ptr, obj) }
    }

    pub fn handle(&self) -> RawHandleObjectVector {
        RawHandleObjectVector {
            ptr: unsafe { GetObjectVectorAddress(self.ptr) },
        }
    }
}

impl Drop for RootedObjectVectorWrapper {
    fn drop(&mut self) {
        unsafe { DeleteRootedObjectVector(self.ptr) }
    }
}

pub struct CompileOptionsWrapper {
    pub ptr: *mut ReadOnlyCompileOptions,
}

impl CompileOptionsWrapper {
    pub unsafe fn new(cx: *mut JSContext, filename: &str, line: u32) -> Self {
        let filename_cstr = ffi::CString::new(filename.as_bytes()).unwrap();
        let ptr = NewCompileOptions(cx, filename_cstr.as_ptr(), line);
        assert!(!ptr.is_null());
        Self { ptr }
    }
}

impl Drop for CompileOptionsWrapper {
    fn drop(&mut self) {
        unsafe { DeleteCompileOptions(self.ptr) }
    }
}

pub struct Stencil {
    inner: already_AddRefed<CompilationStencil>,
}

/*unsafe impl Send for Stencil {}
unsafe impl Sync for Stencil {}*/

impl Drop for Stencil {
    fn drop(&mut self) {
        if self.is_null() {
            return;
        }
        unsafe {
            StencilRelease(self.inner.mRawPtr);
        }
    }
}

impl Deref for Stencil {
    type Target = *mut CompilationStencil;

    fn deref(&self) -> &Self::Target {
        &self.inner.mRawPtr
    }
}

impl Stencil {
    pub fn is_null(&self) -> bool {
        self.inner.mRawPtr.is_null()
    }
}

// ___________________________________________________________________________
// Fast inline converters

#[inline]
pub unsafe fn ToBoolean(v: HandleValue) -> bool {
    let val = *v.ptr;

    if val.is_boolean() {
        return val.to_boolean();
    }

    if val.is_int32() {
        return val.to_int32() != 0;
    }

    if val.is_null_or_undefined() {
        return false;
    }

    if val.is_double() {
        let d = val.to_double();
        return !d.is_nan() && d != 0f64;
    }

    if val.is_symbol() {
        return true;
    }

    ToBooleanSlow(v.into())
}

#[inline]
pub unsafe fn ToNumber(cx: *mut JSContext, v: HandleValue) -> Result<f64, ()> {
    let val = *v.ptr;
    if val.is_number() {
        return Ok(val.to_number());
    }

    let mut out = Default::default();
    if ToNumberSlow(cx, v.into_handle(), &mut out) {
        Ok(out)
    } else {
        Err(())
    }
}

#[inline]
unsafe fn convert_from_int32<T: Default + Copy>(
    cx: *mut JSContext,
    v: HandleValue,
    conv_fn: unsafe extern "C" fn(*mut JSContext, RawHandleValue, *mut T) -> bool,
) -> Result<T, ()> {
    let val = *v.ptr;
    if val.is_int32() {
        let intval: i64 = val.to_int32() as i64;
        // TODO: do something better here that works on big endian
        let intval = *(&intval as *const i64 as *const T);
        return Ok(intval);
    }

    let mut out = Default::default();
    if conv_fn(cx, v.into(), &mut out) {
        Ok(out)
    } else {
        Err(())
    }
}

#[inline]
pub unsafe fn ToInt32(cx: *mut JSContext, v: HandleValue) -> Result<i32, ()> {
    convert_from_int32::<i32>(cx, v, ToInt32Slow)
}

#[inline]
pub unsafe fn ToUint32(cx: *mut JSContext, v: HandleValue) -> Result<u32, ()> {
    convert_from_int32::<u32>(cx, v, ToUint32Slow)
}

#[inline]
pub unsafe fn ToUint16(cx: *mut JSContext, v: HandleValue) -> Result<u16, ()> {
    convert_from_int32::<u16>(cx, v, ToUint16Slow)
}

#[inline]
pub unsafe fn ToInt64(cx: *mut JSContext, v: HandleValue) -> Result<i64, ()> {
    convert_from_int32::<i64>(cx, v, ToInt64Slow)
}

#[inline]
pub unsafe fn ToUint64(cx: *mut JSContext, v: HandleValue) -> Result<u64, ()> {
    convert_from_int32::<u64>(cx, v, ToUint64Slow)
}

#[inline]
pub unsafe fn ToString(cx: *mut JSContext, v: HandleValue) -> *mut JSString {
    let val = *v.ptr;
    if val.is_string() {
        return val.to_string();
    }

    ToStringSlow(cx, v.into())
}

pub unsafe fn ToWindowProxyIfWindow(obj: *mut JSObject) -> *mut JSObject {
    if is_window(obj) {
        ToWindowProxyIfWindowSlow(obj)
    } else {
        obj
    }
}

pub unsafe extern "C" fn report_warning(_cx: *mut JSContext, report: *mut JSErrorReport) {
    fn latin1_to_string(bytes: &[u8]) -> String {
        bytes
            .iter()
            .map(|c| char::from_u32(*c as u32).unwrap())
            .collect()
    }

    let fnptr = (*report)._base.filename.data_;
    let fname = if !fnptr.is_null() {
        let c_str = CStr::from_ptr(fnptr);
        latin1_to_string(c_str.to_bytes())
    } else {
        "none".to_string()
    };

    let lineno = (*report)._base.lineno;
    let column = (*report)._base.column._base;

    let msg_ptr = (*report)._base.message_.data_ as *const u8;
    let msg_len = (0usize..)
        .find(|&i| *msg_ptr.offset(i as isize) == 0)
        .unwrap();
    let msg_slice = slice::from_raw_parts(msg_ptr, msg_len);
    let msg = str::from_utf8_unchecked(msg_slice);

    warn!("Warning at {}:{}:{}: {}\n", fname, lineno, column, msg);
}

pub struct IdVector(*mut PersistentRootedIdVector);

impl IdVector {
    pub unsafe fn new(cx: *mut JSContext) -> IdVector {
        let vector = CreateRootedIdVector(cx);
        assert!(!vector.is_null());
        IdVector(vector)
    }

    pub fn handle_mut(&mut self) -> RawMutableHandleIdVector {
        RawMutableHandleIdVector {
            ptr: unsafe { GetIdVectorAddress(self.0) },
        }
    }
}

impl Drop for IdVector {
    fn drop(&mut self) {
        unsafe { DestroyRootedIdVector(self.0) }
    }
}

impl Deref for IdVector {
    type Target = [jsid];

    fn deref(&self) -> &[jsid] {
        unsafe {
            let mut length = 0;
            let pointer = SliceRootedIdVector(self.0, &mut length);
            slice::from_raw_parts(pointer, length)
        }
    }
}

/// Defines methods on `obj`. The last entry of `methods` must contain zeroed
/// memory.
///
/// # Failures
///
/// Returns `Err` on JSAPI failure.
///
/// # Panics
///
/// Panics if the last entry of `methods` does not contain zeroed memory.
///
/// # Safety
///
/// - `cx` must be valid.
/// - This function calls into unaudited C++ code.
pub unsafe fn define_methods(
    cx: *mut JSContext,
    obj: HandleObject,
    methods: &'static [JSFunctionSpec],
) -> Result<(), ()> {
    assert!({
        match methods.last() {
            Some(&JSFunctionSpec {
                name,
                call,
                nargs,
                flags,
                selfHostedName,
            }) => {
                name.string_.is_null()
                    && call.is_zeroed()
                    && nargs == 0
                    && flags == 0
                    && selfHostedName.is_null()
            }
            None => false,
        }
    });

    JS_DefineFunctions(cx, obj.into(), methods.as_ptr()).to_result()
}

/// Defines attributes on `obj`. The last entry of `properties` must contain
/// zeroed memory.
///
/// # Failures
///
/// Returns `Err` on JSAPI failure.
///
/// # Panics
///
/// Panics if the last entry of `properties` does not contain zeroed memory.
///
/// # Safety
///
/// - `cx` must be valid.
/// - This function calls into unaudited C++ code.
pub unsafe fn define_properties(
    cx: *mut JSContext,
    obj: HandleObject,
    properties: &'static [JSPropertySpec],
) -> Result<(), ()> {
    assert!({
        match properties.last() {
            Some(spec) => spec.is_zeroed(),
            None => false,
        }
    });

    JS_DefineProperties(cx, obj.into(), properties.as_ptr()).to_result()
}

static SIMPLE_GLOBAL_CLASS_OPS: JSClassOps = JSClassOps {
    addProperty: None,
    delProperty: None,
    enumerate: Some(JS_EnumerateStandardClasses),
    newEnumerate: None,
    resolve: Some(JS_ResolveStandardClass),
    mayResolve: Some(JS_MayResolveStandardClass),
    finalize: None,
    call: None,
    construct: None,
    trace: Some(JS_GlobalObjectTraceHook),
};

/// This is a simple `JSClass` for global objects, primarily intended for tests.
pub static SIMPLE_GLOBAL_CLASS: JSClass = JSClass {
    name: b"Global\0" as *const u8 as *const _,
    flags: JSCLASS_IS_GLOBAL
        | ((JSCLASS_GLOBAL_SLOT_COUNT & JSCLASS_RESERVED_SLOTS_MASK)
            << JSCLASS_RESERVED_SLOTS_SHIFT),
    cOps: &SIMPLE_GLOBAL_CLASS_OPS as *const JSClassOps,
    spec: ptr::null(),
    ext: ptr::null(),
    oOps: ptr::null(),
};

#[inline]
unsafe fn get_object_group(obj: *mut JSObject) -> *mut BaseShape {
    assert!(!obj.is_null());
    let obj = obj as *mut Object;
    (*(*obj).shape).base
}

#[inline]
pub unsafe fn get_object_class(obj: *mut JSObject) -> *const JSClass {
    (*get_object_group(obj)).clasp as *const _
}

#[inline]
pub unsafe fn get_object_realm(obj: *mut JSObject) -> *mut Realm {
    (*get_object_group(obj)).realm
}

#[inline]
pub unsafe fn get_context_realm(cx: *mut JSContext) -> *mut Realm {
    let cx = cx as *mut RootingContext;
    (*cx).realm_
}

#[inline]
pub fn is_dom_class(class: &JSClass) -> bool {
    class.flags & JSCLASS_IS_DOMJSCLASS != 0
}

#[inline]
pub unsafe fn is_dom_object(obj: *mut JSObject) -> bool {
    is_dom_class(&*get_object_class(obj))
}

#[inline]
pub unsafe fn is_window(obj: *mut JSObject) -> bool {
    (*get_object_class(obj)).flags & JSCLASS_IS_GLOBAL != 0 && IsWindowSlow(obj)
}

#[inline]
pub unsafe fn try_to_outerize(mut rval: MutableHandleValue) {
    let obj = rval.to_object();
    if is_window(obj) {
        let obj = ToWindowProxyIfWindowSlow(obj);
        assert!(!obj.is_null());
        rval.set(ObjectValue(&mut *obj));
    }
}

#[inline]
pub unsafe fn try_to_outerize_object(mut rval: MutableHandleObject) {
    if is_window(*rval) {
        let obj = ToWindowProxyIfWindowSlow(*rval);
        assert!(!obj.is_null());
        rval.set(obj);
    }
}

#[inline]
pub unsafe fn maybe_wrap_object(cx: *mut JSContext, obj: MutableHandleObject) {
    if get_object_realm(*obj) != get_context_realm(cx) {
        assert!(JS_WrapObject(cx, obj.into()));
    }
    try_to_outerize_object(obj);
}

#[inline]
pub unsafe fn maybe_wrap_object_value(cx: *mut JSContext, rval: MutableHandleValue) {
    assert!(rval.is_object());
    let obj = rval.to_object();
    if get_object_realm(obj) != get_context_realm(cx) {
        assert!(JS_WrapValue(cx, rval.into()));
    } else if is_dom_object(obj) {
        try_to_outerize(rval);
    }
}

#[inline]
pub unsafe fn maybe_wrap_object_or_null_value(cx: *mut JSContext, rval: MutableHandleValue) {
    assert!(rval.is_object_or_null());
    if !rval.is_null() {
        maybe_wrap_object_value(cx, rval);
    }
}

#[inline]
pub unsafe fn maybe_wrap_value(cx: *mut JSContext, rval: MutableHandleValue) {
    if rval.is_string() {
        assert!(JS_WrapValue(cx, rval.into()));
    } else if rval.is_object() {
        maybe_wrap_object_value(cx, rval);
    }
}

/// Like `JSJitInfo::new_bitfield_1`, but usable in `const` contexts.
#[macro_export]
macro_rules! new_jsjitinfo_bitfield_1 {
    (
        $type_: expr,
        $aliasSet_: expr,
        $returnType_: expr,
        $isInfallible: expr,
        $isMovable: expr,
        $isEliminatable: expr,
        $isAlwaysInSlot: expr,
        $isLazilyCachedInSlot: expr,
        $isTypedMethod: expr,
        $slotIndex: expr,
    ) => {
        0 | (($type_ as u32) << 0u32)
            | (($aliasSet_ as u32) << 4u32)
            | (($returnType_ as u32) << 8u32)
            | (($isInfallible as u32) << 16u32)
            | (($isMovable as u32) << 17u32)
            | (($isEliminatable as u32) << 18u32)
            | (($isAlwaysInSlot as u32) << 19u32)
            | (($isLazilyCachedInSlot as u32) << 20u32)
            | (($isTypedMethod as u32) << 21u32)
            | (($slotIndex as u32) << 22u32)
    };
}

#[derive(Debug, Default)]
pub struct ScriptedCaller {
    pub filename: String,
    pub line: u32,
    pub col: u32,
}

pub unsafe fn describe_scripted_caller(cx: *mut JSContext) -> Result<ScriptedCaller, ()> {
    let mut buf = [0; 1024];
    let mut line = 0;
    let mut col = 0;
    if !DescribeScriptedCaller(cx, buf.as_mut_ptr(), buf.len(), &mut line, &mut col) {
        return Err(());
    }
    let filename = CStr::from_ptr((&buf) as *const _ as *const _);
    Ok(ScriptedCaller {
        filename: String::from_utf8_lossy(filename.to_bytes()).into_owned(),
        line,
        col,
    })
}

pub struct CapturedJSStack<'a> {
    cx: *mut JSContext,
    stack: RootedGuard<'a, *mut JSObject>,
}

impl<'a> CapturedJSStack<'a> {
    pub unsafe fn new(
        cx: *mut JSContext,
        mut guard: RootedGuard<'a, *mut JSObject>,
        max_frame_count: Option<u32>,
    ) -> Option<Self> {
        let ref mut stack_capture = MaybeUninit::uninit();
        match max_frame_count {
            None => JS_StackCapture_AllFrames(stack_capture.as_mut_ptr()),
            Some(count) => JS_StackCapture_MaxFrames(count, stack_capture.as_mut_ptr()),
        };
        let ref mut stack_capture = stack_capture.assume_init();

        if !CaptureCurrentStack(cx, guard.handle_mut().raw(), stack_capture) {
            None
        } else {
            Some(CapturedJSStack { cx, stack: guard })
        }
    }

    pub fn as_string(&self, indent: Option<usize>, format: StackFormat) -> Option<String> {
        unsafe {
            let stack_handle = self.stack.handle();
            rooted!(in(self.cx) let mut js_string = ptr::null_mut::<JSString>());
            let mut string_handle = js_string.handle_mut();

            if !BuildStackString(
                self.cx,
                ptr::null_mut(),
                stack_handle.into(),
                string_handle.raw(),
                indent.unwrap_or(0),
                format,
            ) {
                return None;
            }

            Some(jsstr_to_string(self.cx, string_handle.get()))
        }
    }
}

#[macro_export]
macro_rules! capture_stack {
    (in($cx:expr) let $name:ident = with max depth($max_frame_count:expr)) => {
        rooted!(in($cx) let mut __obj = ::std::ptr::null_mut());
        let $name = $crate::rust::CapturedJSStack::new($cx, __obj, Some($max_frame_count));
    };
    (in($cx:expr) let $name:ident ) => {
        rooted!(in($cx) let mut __obj = ::std::ptr::null_mut());
        let $name = $crate::rust::CapturedJSStack::new($cx, __obj, None);
    }
}

/** Wrappers for JSAPI methods that should NOT be used.
 *
 * The wrapped methods are identical except that they accept Handle and MutableHandle arguments
 * that include lifetimes instead.
 *
 * They require MutableHandles to implement Copy. All code should migrate to jsapi_wrapped instead.
 * */
pub mod wrappers {
    macro_rules! wrap {
        // The invocation of @inner has the following form:
        // @inner (input args) <> (accumulator) <> unparsed tokens
        // when `unparsed tokens == \eps`, accumulator contains the final result

        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: Handle<$gentype:ty>, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandle<$gentype:ty>, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: Handle, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandle, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleFunction , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleId , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleObject , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleScript , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleString , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleSymbol , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: HandleValue , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleFunction , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleId , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleObject , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleScript , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleString , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleSymbol , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: MutableHandleValue , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($acc:expr,)*) <> $arg:ident: $type:ty, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($acc,)* $arg,) <> $($rest)*);
        };
        (@inner ($module:tt: $func_name:ident ($($args:tt)*) -> $outtype:ty) <> ($($argexprs:expr,)*) <> ) => {
            #[inline]
            pub unsafe fn $func_name($($args)*) -> $outtype {
                $module::$func_name($($argexprs),*)
            }
        };
        ($module:tt: pub fn $func_name:ident($($args:tt)*) -> $outtype:ty) => {
            wrap!(@inner ($module: $func_name ($($args)*) -> $outtype) <> () <> $($args)* ,);
        };
        ($module:tt: pub fn $func_name:ident($($args:tt)*)) => {
            wrap!($module: pub fn $func_name($($args)*) -> ());
        }
    }

    use super::*;
    use crate::glue;
    use crate::glue::EncodedStringCallback;
    use crate::jsapi;
    use crate::jsapi::jsid;
    use crate::jsapi::mozilla::Utf8Unit;
    use crate::jsapi::BigInt;
    use crate::jsapi::CallArgs;
    use crate::jsapi::CloneDataPolicy;
    use crate::jsapi::ColumnNumberOneOrigin;
    use crate::jsapi::CompartmentTransplantCallback;
    use crate::jsapi::JSONParseHandler;
    use crate::jsapi::Latin1Char;
    use crate::jsapi::PropertyKey;
    use crate::jsapi::TaggedColumnNumberOneOrigin;
    //use jsapi::DynamicImportStatus;
    use crate::jsapi::ESClass;
    use crate::jsapi::ExceptionStackBehavior;
    use crate::jsapi::ForOfIterator;
    use crate::jsapi::ForOfIterator_NonIterableBehavior;
    use crate::jsapi::HandleObjectVector;
    use crate::jsapi::InstantiateOptions;
    use crate::jsapi::JSClass;
    use crate::jsapi::JSErrorReport;
    use crate::jsapi::JSExnType;
    use crate::jsapi::JSFunctionSpecWithHelp;
    use crate::jsapi::JSJitInfo;
    use crate::jsapi::JSONWriteCallback;
    use crate::jsapi::JSPrincipals;
    use crate::jsapi::JSPropertySpec;
    use crate::jsapi::JSPropertySpec_Name;
    use crate::jsapi::JSProtoKey;
    use crate::jsapi::JSScript;
    use crate::jsapi::JSStructuredCloneData;
    use crate::jsapi::JSType;
    use crate::jsapi::ModuleErrorBehaviour;
    use crate::jsapi::MutableHandleIdVector;
    use crate::jsapi::PromiseState;
    use crate::jsapi::PromiseUserInputEventHandlingState;
    use crate::jsapi::ReadOnlyCompileOptions;
    use crate::jsapi::ReadableStreamMode;
    use crate::jsapi::ReadableStreamReaderMode;
    use crate::jsapi::ReadableStreamUnderlyingSource;
    use crate::jsapi::Realm;
    use crate::jsapi::RefPtr;
    use crate::jsapi::RegExpFlags;
    use crate::jsapi::ScriptEnvironmentPreparer_Closure;
    use crate::jsapi::SourceText;
    use crate::jsapi::StackCapture;
    use crate::jsapi::StructuredCloneScope;
    use crate::jsapi::Symbol;
    use crate::jsapi::SymbolCode;
    use crate::jsapi::TwoByteChars;
    use crate::jsapi::UniqueChars;
    use crate::jsapi::Value;
    use crate::jsapi::WasmModule;
    use crate::jsapi::{ElementAdder, IsArrayAnswer, PropertyDescriptor};
    use crate::jsapi::{JSContext, JSFunction, JSNative, JSObject, JSString};
    use crate::jsapi::{
        JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter,
    };
    use crate::jsapi::{MallocSizeOf, ObjectOpResult, ObjectPrivateVisitor, TabSizes};
    use crate::jsapi::{SavedFrameResult, SavedFrameSelfHosted};
    include!("jsapi_wrappers.in");
    include!("glue_wrappers.in");
}

/** Wrappers for JSAPI methods that accept lifetimed Handle and MutableHandle arguments.
 *
 * The wrapped methods are identical except that they accept Handle and MutableHandle arguments
 * that include lifetimes instead. Besides, they mutably borrow the mutable handles
 * instead of consuming/copying them.
 *
 * These wrappers are preferred, js::rust::wrappers should NOT be used.
 * */
pub mod jsapi_wrapped {
    macro_rules! wrap {
        // The invocation of @inner has the following form:
        // @inner (input args) <> (argument accumulator) <> (invocation accumulator) <> unparsed tokens
        // when `unparsed tokens == \eps`, accumulator contains the final result

        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: Handle<$gentype:ty>, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: Handle<$gentype> , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandle<$gentype:ty>, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandle<$gentype> , )  <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: Handle, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: Handle , )  <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandle, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandle , )  <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleFunction , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleFunction , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleId , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleId , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleObject , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleObject , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleScript , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleScript , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleString , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleString , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleSymbol , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleSymbol , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: HandleValue , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: HandleValue , ) <> ($($acc,)* $arg.into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleFunction , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleFunction , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleId , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleId , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleObject , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleObject , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleScript , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleScript , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleString , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleString , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleSymbol , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleSymbol , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <> ($($acc:expr,)*) <> $arg:ident: MutableHandleValue , $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: &mut MutableHandleValue , ) <> ($($acc,)* (*$arg).into(),) <> $($rest)*);
        };
        (@inner $saved:tt <> ($($declargs:tt)*) <>  ($($acc:expr,)*) <> $arg:ident: $type:ty, $($rest:tt)*) => {
            wrap!(@inner $saved <> ($($declargs)* $arg: $type,) <> ($($acc,)* $arg,) <> $($rest)*);
        };
        (@inner ($module:tt: $func_name:ident ($($args:tt)*) -> $outtype:ty) <> ($($declargs:tt)*) <> ($($argexprs:expr,)*) <> ) => {
            #[inline]
            pub unsafe fn $func_name($($declargs)*) -> $outtype {
                $module::$func_name($($argexprs),*)
            }
        };
        ($module:tt: pub fn $func_name:ident($($args:tt)*) -> $outtype:ty) => {
            wrap!(@inner ($module: $func_name ($($args)*) -> $outtype) <> () <> () <> $($args)* ,);
        };
        ($module:tt: pub fn $func_name:ident($($args:tt)*)) => {
            wrap!($module: pub fn $func_name($($args)*) -> ());
        }
    }

    use super::*;
    use crate::glue;
    use crate::glue::EncodedStringCallback;
    use crate::jsapi;
    use crate::jsapi::mozilla::Utf8Unit;
    use crate::jsapi::BigInt;
    use crate::jsapi::CallArgs;
    use crate::jsapi::CloneDataPolicy;
    use crate::jsapi::ColumnNumberOneOrigin;
    use crate::jsapi::CompartmentTransplantCallback;
    use crate::jsapi::ESClass;
    use crate::jsapi::ExceptionStackBehavior;
    use crate::jsapi::ForOfIterator;
    use crate::jsapi::ForOfIterator_NonIterableBehavior;
    use crate::jsapi::HandleObjectVector;
    use crate::jsapi::InstantiateOptions;
    use crate::jsapi::JSClass;
    use crate::jsapi::JSErrorReport;
    use crate::jsapi::JSExnType;
    use crate::jsapi::JSFunctionSpec;
    use crate::jsapi::JSFunctionSpecWithHelp;
    use crate::jsapi::JSJitInfo;
    use crate::jsapi::JSONParseHandler;
    use crate::jsapi::JSONWriteCallback;
    use crate::jsapi::JSPrincipals;
    use crate::jsapi::JSPropertySpec;
    use crate::jsapi::JSPropertySpec_Name;
    use crate::jsapi::JSProtoKey;
    use crate::jsapi::JSScript;
    use crate::jsapi::JSStructuredCloneData;
    use crate::jsapi::JSType;
    use crate::jsapi::Latin1Char;
    use crate::jsapi::ModuleErrorBehaviour;
    use crate::jsapi::MutableHandleIdVector;
    use crate::jsapi::PromiseState;
    use crate::jsapi::PromiseUserInputEventHandlingState;
    use crate::jsapi::PropertyKey;
    use crate::jsapi::ReadOnlyCompileOptions;
    use crate::jsapi::ReadableStreamMode;
    use crate::jsapi::ReadableStreamReaderMode;
    use crate::jsapi::ReadableStreamUnderlyingSource;
    use crate::jsapi::Realm;
    use crate::jsapi::RefPtr;
    use crate::jsapi::RegExpFlags;
    use crate::jsapi::ScriptEnvironmentPreparer_Closure;
    use crate::jsapi::SourceText;
    use crate::jsapi::StackCapture;
    use crate::jsapi::StructuredCloneScope;
    use crate::jsapi::Symbol;
    use crate::jsapi::SymbolCode;
    use crate::jsapi::TaggedColumnNumberOneOrigin;
    use crate::jsapi::TwoByteChars;
    use crate::jsapi::UniqueChars;
    use crate::jsapi::Value;
    use crate::jsapi::WasmModule;
    use crate::jsapi::{ElementAdder, IsArrayAnswer, PropertyDescriptor};
    use crate::jsapi::{JSContext, JSFunction, JSNative, JSObject, JSString};
    use crate::jsapi::{
        JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter,
    };
    use crate::jsapi::{MallocSizeOf, ObjectOpResult, ObjectPrivateVisitor, TabSizes};
    use crate::jsapi::{SavedFrameResult, SavedFrameSelfHosted};
    include!("jsapi_wrappers.in");
    include!("glue_wrappers.in");
}