Skip to main content

wasm_bindgen/
lib.rs

1//! Runtime support for the `wasm-bindgen` tool
2//!
3//! This crate contains the runtime support necessary for `wasm-bindgen` the
4//! attribute and tool. Crates pull in the `#[wasm_bindgen]` attribute through
5//! this crate and this crate also provides JS bindings through the `JsValue`
6//! interface.
7//!
8//! ## Features
9//!
10//! ### `enable-interning`
11//!
12//! Enables the internal cache for [`wasm_bindgen::intern`].
13//!
14//! This feature currently enables the `std` feature, meaning that it is not
15//! compatible with `no_std` environments.
16//!
17//! ### `std` (default)
18//!
19//! Enabling this feature will make the crate depend on the Rust standard library.
20//!
21//! Disable this feature to use this crate in `no_std` environments.
22//!
23//! ### `strict-macro`
24//!
25//! All warnings the `#[wasm_bindgen]` macro emits are turned into hard errors.
26//! This mainly affects unused attribute options.
27//!
28//! ### Deprecated features
29//!
30//! #### `serde-serialize`
31//!
32//! **Deprecated:** Use the [`serde-wasm-bindgen`](https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/) crate instead.
33//!
34//! Enables the `JsValue::from_serde` and `JsValue::into_serde` methods for
35//! serializing and deserializing Rust types to and from JavaScript.
36//!
37//! #### `spans`
38//!
39//! **Deprecated:** This feature became a no-op in wasm-bindgen v0.2.20 (Sep 7, 2018).
40
41#![no_std]
42#![cfg_attr(wasm_bindgen_unstable_test_coverage, feature(coverage_attribute))]
43#![cfg_attr(
44    wasm_bindgen_unstable_try_trait,
45    feature(try_trait_v2, try_trait_v2_residual)
46)]
47#![cfg_attr(target_feature = "atomics", feature(thread_local))]
48#![cfg_attr(
49    any(target_feature = "atomics", wasm_bindgen_unstable_test_coverage),
50    feature(allow_internal_unstable),
51    allow(internal_features)
52)]
53#![cfg_attr(
54    all(not(debug_assertions), not(feature = "std"), target_arch = "wasm64"),
55    feature(simd_wasm64)
56)]
57#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")]
58
59extern crate alloc;
60#[cfg(feature = "std")]
61extern crate std;
62
63use crate::convert::{TryFromJsValue, UpcastFrom, VectorIntoWasmAbi};
64use crate::sys::Promising;
65use alloc::boxed::Box;
66use alloc::string::String;
67use alloc::vec::Vec;
68use core::convert::TryFrom;
69use core::marker::PhantomData;
70use core::ops::{
71    Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub,
72};
73use core::ptr::NonNull;
74
75const _: () = {
76    /// Dummy empty function provided in order to detect linker-injected functions like `__wasm_call_ctors` and others that should be skipped by the wasm-bindgen interpreter.
77    ///
78    /// ## About `__wasm_call_ctors`
79    ///
80    /// There are several ways `__wasm_call_ctors` is introduced by the linker:
81    ///
82    /// * Using `#[link_section = ".init_array"]`;
83    /// * Linking with a C library that uses `__attribute__((constructor))`.
84    ///
85    /// The Wasm linker will insert a call to the `__wasm_call_ctors` function at the beginning of every
86    /// function that your module exports if it regards a module as having "command-style linkage".
87    /// Specifically, it regards a module as having "command-style linkage" if:
88    ///
89    /// * it is not relocatable;
90    /// * it is not a position-independent executable;
91    /// * and it does not call `__wasm_call_ctors`, directly or indirectly, from any
92    ///   exported function.
93    #[no_mangle]
94    pub extern "C" fn __wbindgen_skip_interpret_calls() {}
95
96    /// A custom data section used to detect Emscripten.
97    #[cfg(target_os = "emscripten")]
98    #[link_section = "__wasm_bindgen_emscripten_marker"]
99    static __WASM_BINDGEN_EMSCRIPTEN_MARKER: [u8; 1] = [1];
100
101    /// A custom data section telling the CLI that the runtime was built with
102    /// `--cfg wasm_bindgen_unstable_jspi`, so JSPI on Emscripten goes through
103    /// its lifecycle hooks rather than wasm-bindgen's own stack management.
104    #[cfg(all(target_os = "emscripten", wasm_bindgen_unstable_jspi))]
105    #[link_section = "__wasm_bindgen_emscripten_jspi_marker"]
106    static __WASM_BINDGEN_EMSCRIPTEN_JSPI_MARKER: [u8; 1] = [1];
107};
108
109macro_rules! externs {
110    ($(#[$attr:meta])* extern "C" { $(fn $name:ident($($args:tt)*) -> $ret:ty;)* }) => (
111        #[cfg(all(target_family = "wasm", not(target_os = "wasi")))]
112        $(#[$attr])*
113        extern "C" {
114            $(fn $name($($args)*) -> $ret;)*
115        }
116
117        $(
118            #[cfg(not(all(target_family = "wasm", not(target_os = "wasi"))))]
119            #[allow(unused_variables)]
120            unsafe extern "C" fn $name($($args)*) -> $ret {
121                panic!("function not implemented on non-wasm32 targets")
122            }
123        )*
124    )
125}
126
127/// A module which is typically glob imported.
128///
129/// ```
130/// use wasm_bindgen::prelude::*;
131/// ```
132pub mod prelude {
133    pub use crate::closure::{Closure, ScopedClosure};
134    pub use crate::convert::Upcast; // provides upcast() and upcast_ref()
135    pub use crate::JsCast;
136    pub use crate::JsValue;
137    pub use crate::Nullable;
138    pub use crate::UnwrapThrowExt;
139    #[doc(hidden)]
140    pub use wasm_bindgen_macro::__wasm_bindgen_class_marker;
141    pub use wasm_bindgen_macro::wasm_bindgen;
142
143    pub use crate::JsError;
144}
145
146pub use wasm_bindgen_macro::link_to;
147
148pub mod closure;
149pub mod convert;
150pub mod describe;
151mod link;
152mod nullable;
153mod safe_integer;
154pub mod sys;
155
156pub use crate::nullable::Nullable;
157pub use crate::safe_integer::{SafeI64, SafeInteger, SafeIntegerPrimitive, SafeU64};
158
159#[cfg(wbg_reference_types)]
160mod externref;
161#[cfg(wbg_reference_types)]
162use externref::__wbindgen_externref_heap_live_count;
163
164pub use crate::__rt::marker::ErasableGeneric;
165pub use crate::convert::{IntoJsGeneric, JsGeneric, JsStringLike};
166
167#[doc(hidden)]
168pub mod handler;
169
170mod cast;
171pub use crate::cast::JsCast;
172
173mod parent;
174pub use crate::parent::Parent;
175
176mod cache;
177pub use cache::intern::{intern, unintern};
178
179#[doc(hidden)]
180#[path = "rt/mod.rs"]
181pub mod __rt;
182use __rt::wbg_cast;
183
184/// Representation of an object owned by JS.
185///
186/// A `JsValue` doesn't actually live in Rust right now but actually in a table
187/// owned by the `wasm-bindgen` generated JS glue code. Eventually the ownership
188/// will transfer into Wasm directly and this will likely become more efficient,
189/// but for now it may be slightly slow.
190pub struct JsValue {
191    idx: u32,
192    _marker: PhantomData<*mut u8>, // not at all threadsafe
193}
194
195#[cfg(not(target_feature = "atomics"))]
196unsafe impl Send for JsValue {}
197#[cfg(not(target_feature = "atomics"))]
198unsafe impl Sync for JsValue {}
199
200unsafe impl ErasableGeneric for JsValue {
201    type Repr = JsValue;
202}
203
204impl Promising for JsValue {
205    type Resolution = JsValue;
206}
207
208impl JsValue {
209    /// The `null` JS value constant.
210    pub const NULL: JsValue = JsValue::_new(__rt::JSIDX_NULL);
211
212    /// The `undefined` JS value constant.
213    pub const UNDEFINED: JsValue = JsValue::_new(__rt::JSIDX_UNDEFINED);
214
215    /// The `true` JS value constant.
216    pub const TRUE: JsValue = JsValue::_new(__rt::JSIDX_TRUE);
217
218    /// The `false` JS value constant.
219    pub const FALSE: JsValue = JsValue::_new(__rt::JSIDX_FALSE);
220
221    #[inline]
222    const fn _new(idx: u32) -> JsValue {
223        JsValue {
224            idx,
225            _marker: PhantomData,
226        }
227    }
228
229    /// Creates a new JS value which is a string.
230    ///
231    /// The utf-8 string provided is copied to the JS heap and the string will
232    /// be owned by the JS garbage collector.
233    #[allow(clippy::should_implement_trait)] // cannot fix without breaking change
234    #[inline]
235    pub fn from_str(s: &str) -> JsValue {
236        wbg_cast(s)
237    }
238
239    /// Creates a new JS value which is a string, decoding `bytes` as UTF-8.
240    ///
241    /// Invalid UTF-8 sequences are replaced with U+FFFD, so this behaves like
242    /// `JsValue::from_str(&String::from_utf8_lossy(bytes))` without the
243    /// intermediate Rust allocation: the bytes are decoded directly from
244    /// Wasm memory on the JS side.
245    #[inline]
246    pub fn from_utf8_lossy(bytes: &[u8]) -> JsValue {
247        #[cfg(feature = "enable-interning")]
248        if let Some(value) = cache::intern::get_bytes(bytes) {
249            return value;
250        }
251        __wbindgen_string_from_utf8_lossy(bytes)
252    }
253
254    /// Creates a new JS value which is a number.
255    ///
256    /// This function creates a JS value representing a number (a heap
257    /// allocated number) and returns a handle to the JS version of it.
258    #[inline]
259    pub fn from_f64(n: f64) -> JsValue {
260        wbg_cast(n)
261    }
262
263    /// Creates a new JS value which is a bigint from a string representing a number.
264    ///
265    /// This function creates a JS value representing a bigint (a heap
266    /// allocated large integer) and returns a handle to the JS version of it.
267    #[inline]
268    pub fn bigint_from_str(s: &str) -> JsValue {
269        __wbindgen_bigint_from_str(s)
270    }
271
272    /// Creates a new JS value which is a boolean.
273    ///
274    /// This function creates a JS object representing a boolean (a heap
275    /// allocated boolean) and returns a handle to the JS version of it.
276    #[inline]
277    pub const fn from_bool(b: bool) -> JsValue {
278        if b {
279            JsValue::TRUE
280        } else {
281            JsValue::FALSE
282        }
283    }
284
285    /// Creates a new JS value representing `undefined`.
286    #[inline]
287    pub const fn undefined() -> JsValue {
288        JsValue::UNDEFINED
289    }
290
291    /// Creates a new JS value representing `null`.
292    #[inline]
293    pub const fn null() -> JsValue {
294        JsValue::NULL
295    }
296
297    /// Creates a new JS symbol with the optional description specified.
298    ///
299    /// This function will invoke the `Symbol` constructor in JS and return the
300    /// JS object corresponding to the symbol created.
301    pub fn symbol(description: Option<&str>) -> JsValue {
302        __wbindgen_symbol_new(description)
303    }
304
305    /// Creates a new `JsValue` from the JSON serialization of the object `t`
306    /// provided.
307    ///
308    /// **This function is deprecated**, due to [creating a dependency cycle in
309    /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
310    /// [`gloo_utils::format::JsValueSerdeExt`] instead.
311    ///
312    /// [dep-cycle-issue]: https://github.com/wasm-bindgen/wasm-bindgen/issues/2770
313    /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
314    /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
315    ///
316    /// This function will serialize the provided value `t` to a JSON string,
317    /// send the JSON string to JS, parse it into a JS object, and then return
318    /// a handle to the JS object. This is unlikely to be super speedy so it's
319    /// not recommended for large payloads, but it's a nice to have in some
320    /// situations!
321    ///
322    /// Usage of this API requires activating the `serde-serialize` feature of
323    /// the `wasm-bindgen` crate.
324    ///
325    /// # Errors
326    ///
327    /// Returns any error encountered when serializing `T` into JSON.
328    #[cfg(feature = "serde-serialize")]
329    #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
330    pub fn from_serde<T>(t: &T) -> serde_json::Result<JsValue>
331    where
332        T: serde::ser::Serialize + ?Sized,
333    {
334        let s = serde_json::to_string(t)?;
335        Ok(__wbindgen_json_parse(s))
336    }
337
338    /// Invokes `JSON.stringify` on this value and then parses the resulting
339    /// JSON into an arbitrary Rust value.
340    ///
341    /// **This function is deprecated**, due to [creating a dependency cycle in
342    /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
343    /// [`gloo_utils::format::JsValueSerdeExt`] instead.
344    ///
345    /// [dep-cycle-issue]: https://github.com/wasm-bindgen/wasm-bindgen/issues/2770
346    /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
347    /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
348    ///
349    /// This function will first call `JSON.stringify` on the `JsValue` itself.
350    /// The resulting string is then passed into Rust which then parses it as
351    /// JSON into the resulting value.
352    ///
353    /// Usage of this API requires activating the `serde-serialize` feature of
354    /// the `wasm-bindgen` crate.
355    ///
356    /// # Errors
357    ///
358    /// Returns any error encountered when parsing the JSON into a `T`.
359    #[cfg(feature = "serde-serialize")]
360    #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
361    pub fn into_serde<T>(&self) -> serde_json::Result<T>
362    where
363        T: for<'a> serde::de::Deserialize<'a>,
364    {
365        let s = __wbindgen_json_serialize(self);
366        // Turns out `JSON.stringify(undefined) === undefined`, so if
367        // we're passed `undefined` reinterpret it as `null` for JSON
368        // purposes.
369        serde_json::from_str(s.as_deref().unwrap_or("null"))
370    }
371
372    /// Returns the `f64` value of this JS value if it's an instance of a
373    /// number.
374    ///
375    /// If this JS value is not an instance of a number then this returns
376    /// `None`.
377    #[inline]
378    pub fn as_f64(&self) -> Option<f64> {
379        __wbindgen_number_get(self)
380    }
381
382    /// Tests whether this JS value is a JS string.
383    #[inline]
384    pub fn is_string(&self) -> bool {
385        __wbindgen_is_string(self)
386    }
387
388    /// If this JS value is a string value, this function copies the JS string
389    /// value into Wasm linear memory, encoded as UTF-8, and returns it as a
390    /// Rust `String`.
391    ///
392    /// To avoid the copying and re-encoding, consider the
393    /// `JsString::try_from()` function from [js-sys](https://docs.rs/js-sys)
394    /// instead.
395    ///
396    /// If this JS value is not an instance of a string or if it's not valid
397    /// utf-8 then this returns `None`.
398    ///
399    /// # UTF-16 vs UTF-8
400    ///
401    /// JavaScript strings in general are encoded as UTF-16, but Rust strings
402    /// are encoded as UTF-8. This can cause the Rust string to look a bit
403    /// different than the JS string sometimes. For more details see the
404    /// [documentation about the `str` type][caveats] which contains a few
405    /// caveats about the encodings.
406    ///
407    /// [caveats]: https://wasm-bindgen.github.io/wasm-bindgen/reference/types/str.html
408    #[inline]
409    pub fn as_string(&self) -> Option<String> {
410        __wbindgen_string_get(self)
411    }
412
413    /// Returns the `bool` value of this JS value if it's an instance of a
414    /// boolean.
415    ///
416    /// If this JS value is not an instance of a boolean then this returns
417    /// `None`.
418    #[inline]
419    pub fn as_bool(&self) -> Option<bool> {
420        __wbindgen_boolean_get(self)
421    }
422
423    /// Tests whether this JS value is `null`
424    #[inline]
425    pub fn is_null(&self) -> bool {
426        __wbindgen_is_null(self)
427    }
428
429    /// Tests whether this JS value is `undefined`
430    #[inline]
431    pub fn is_undefined(&self) -> bool {
432        __wbindgen_is_undefined(self)
433    }
434
435    /// Tests whether this JS value is `null` or `undefined`
436    #[inline]
437    pub fn is_null_or_undefined(&self) -> bool {
438        __wbindgen_is_null_or_undefined(self)
439    }
440
441    /// Tests whether the type of this JS value is `symbol`
442    #[inline]
443    pub fn is_symbol(&self) -> bool {
444        __wbindgen_is_symbol(self)
445    }
446
447    /// Tests whether `typeof self == "object" && self !== null`.
448    #[inline]
449    pub fn is_object(&self) -> bool {
450        __wbindgen_is_object(self)
451    }
452
453    /// Tests whether this JS value is an instance of Array.
454    #[inline]
455    pub fn is_array(&self) -> bool {
456        __wbindgen_is_array(self)
457    }
458
459    /// Tests whether the type of this JS value is `function`.
460    #[inline]
461    pub fn is_function(&self) -> bool {
462        __wbindgen_is_function(self)
463    }
464
465    /// Tests whether the type of this JS value is `bigint`.
466    #[inline]
467    pub fn is_bigint(&self) -> bool {
468        __wbindgen_is_bigint(self)
469    }
470
471    /// Applies the unary `typeof` JS operator on a `JsValue`.
472    ///
473    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
474    #[inline]
475    pub fn js_typeof(&self) -> JsValue {
476        __wbindgen_typeof(self)
477    }
478
479    /// Applies the binary `in` JS operator on the two `JsValue`s.
480    ///
481    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)
482    #[inline]
483    pub fn js_in(&self, obj: &JsValue) -> bool {
484        __wbindgen_in(self, obj)
485    }
486
487    /// Tests whether the value is ["truthy"].
488    ///
489    /// ["truthy"]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
490    #[inline]
491    pub fn is_truthy(&self) -> bool {
492        !self.is_falsy()
493    }
494
495    /// Tests whether the value is ["falsy"].
496    ///
497    /// ["falsy"]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
498    #[inline]
499    pub fn is_falsy(&self) -> bool {
500        __wbindgen_is_falsy(self)
501    }
502
503    /// Get a string representation of the JavaScript object for debugging.
504    fn as_debug_string(&self) -> String {
505        __wbindgen_debug_string(self)
506    }
507
508    /// Compare two `JsValue`s for equality, using the `==` operator in JS.
509    ///
510    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
511    #[inline]
512    pub fn loose_eq(&self, other: &Self) -> bool {
513        __wbindgen_jsval_loose_eq(self, other)
514    }
515
516    /// Applies the unary `~` JS operator on a `JsValue`.
517    ///
518    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT)
519    #[inline]
520    pub fn bit_not(&self) -> JsValue {
521        __wbindgen_bit_not(self)
522    }
523
524    /// Applies the binary `>>>` JS operator on the two `JsValue`s.
525    ///
526    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift)
527    #[inline]
528    pub fn unsigned_shr(&self, rhs: &Self) -> u32 {
529        __wbindgen_unsigned_shr(self, rhs)
530    }
531
532    /// Applies the binary `/` JS operator on two `JsValue`s, catching and returning any `RangeError` thrown.
533    ///
534    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
535    #[inline]
536    pub fn checked_div(&self, rhs: &Self) -> Self {
537        __wbindgen_checked_div(self, rhs)
538    }
539
540    /// Applies the binary `**` JS operator on the two `JsValue`s.
541    ///
542    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
543    #[inline]
544    pub fn pow(&self, rhs: &Self) -> Self {
545        __wbindgen_pow(self, rhs)
546    }
547
548    /// Applies the binary `<` JS operator on the two `JsValue`s.
549    ///
550    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than)
551    #[inline]
552    pub fn lt(&self, other: &Self) -> bool {
553        __wbindgen_lt(self, other)
554    }
555
556    /// Applies the binary `<=` JS operator on the two `JsValue`s.
557    ///
558    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
559    #[inline]
560    pub fn le(&self, other: &Self) -> bool {
561        __wbindgen_le(self, other)
562    }
563
564    /// Applies the binary `>=` JS operator on the two `JsValue`s.
565    ///
566    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal)
567    #[inline]
568    pub fn ge(&self, other: &Self) -> bool {
569        __wbindgen_ge(self, other)
570    }
571
572    /// Applies the binary `>` JS operator on the two `JsValue`s.
573    ///
574    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than)
575    #[inline]
576    pub fn gt(&self, other: &Self) -> bool {
577        __wbindgen_gt(self, other)
578    }
579
580    /// Applies the unary `+` JS operator on a `JsValue`. Can throw.
581    ///
582    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
583    #[inline]
584    pub fn unchecked_into_f64(&self) -> f64 {
585        // Can't use `wbg_cast` here because it expects that the value already has a correct type
586        // and will fail with an assertion error in debug mode.
587        __wbindgen_as_number(self)
588    }
589}
590
591impl PartialEq for JsValue {
592    /// Compares two `JsValue`s for equality, using the `===` operator in JS.
593    ///
594    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
595    #[inline]
596    fn eq(&self, other: &Self) -> bool {
597        __wbindgen_jsval_eq(self, other)
598    }
599}
600
601impl PartialEq<bool> for JsValue {
602    #[inline]
603    fn eq(&self, other: &bool) -> bool {
604        self.as_bool() == Some(*other)
605    }
606}
607
608impl PartialEq<str> for JsValue {
609    #[inline]
610    fn eq(&self, other: &str) -> bool {
611        *self == JsValue::from_str(other)
612    }
613}
614
615impl<'a> PartialEq<&'a str> for JsValue {
616    #[inline]
617    fn eq(&self, other: &&'a str) -> bool {
618        <JsValue as PartialEq<str>>::eq(self, other)
619    }
620}
621
622impl PartialEq<String> for JsValue {
623    #[inline]
624    fn eq(&self, other: &String) -> bool {
625        <JsValue as PartialEq<str>>::eq(self, other)
626    }
627}
628impl<'a> PartialEq<&'a String> for JsValue {
629    #[inline]
630    fn eq(&self, other: &&'a String) -> bool {
631        <JsValue as PartialEq<str>>::eq(self, other)
632    }
633}
634
635macro_rules! forward_deref_unop {
636    (impl $imp:ident, $method:ident for $t:ty) => {
637        impl $imp for $t {
638            type Output = <&'static $t as $imp>::Output;
639
640            #[inline]
641            fn $method(self) -> <&'static $t as $imp>::Output {
642                $imp::$method(&self)
643            }
644        }
645    };
646}
647
648macro_rules! forward_deref_binop {
649    (impl $imp:ident, $method:ident for $t:ty) => {
650        impl<'a> $imp<$t> for &'a $t {
651            type Output = <&'static $t as $imp<&'static $t>>::Output;
652
653            #[inline]
654            fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
655                $imp::$method(self, &other)
656            }
657        }
658
659        impl $imp<&$t> for $t {
660            type Output = <&'static $t as $imp<&'static $t>>::Output;
661
662            #[inline]
663            fn $method(self, other: &$t) -> <&'static $t as $imp<&'static $t>>::Output {
664                $imp::$method(&self, other)
665            }
666        }
667
668        impl $imp<$t> for $t {
669            type Output = <&'static $t as $imp<&'static $t>>::Output;
670
671            #[inline]
672            fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
673                $imp::$method(&self, &other)
674            }
675        }
676    };
677}
678
679impl Not for &JsValue {
680    type Output = bool;
681
682    /// Applies the `!` JS operator on a `JsValue`.
683    ///
684    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT)
685    #[inline]
686    fn not(self) -> Self::Output {
687        JsValue::is_falsy(self)
688    }
689}
690
691forward_deref_unop!(impl Not, not for JsValue);
692
693impl TryFrom<JsValue> for f64 {
694    type Error = JsValue;
695
696    /// Applies the unary `+` JS operator on a `JsValue`.
697    /// Returns the numeric result on success, or the JS error value on error.
698    ///
699    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
700    #[inline]
701    fn try_from(val: JsValue) -> Result<Self, Self::Error> {
702        f64::try_from(&val)
703    }
704}
705
706impl TryFrom<&JsValue> for f64 {
707    type Error = JsValue;
708
709    /// Applies the unary `+` JS operator on a `JsValue`.
710    /// Returns the numeric result on success, or the JS error value on error.
711    ///
712    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
713    #[inline]
714    fn try_from(val: &JsValue) -> Result<Self, Self::Error> {
715        let jsval = __wbindgen_try_into_number(val);
716        match jsval.as_f64() {
717            Some(num) => Ok(num),
718            None => Err(jsval),
719        }
720    }
721}
722
723impl Neg for &JsValue {
724    type Output = JsValue;
725
726    /// Applies the unary `-` JS operator on a `JsValue`.
727    ///
728    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
729    #[inline]
730    fn neg(self) -> Self::Output {
731        __wbindgen_neg(self)
732    }
733}
734
735forward_deref_unop!(impl Neg, neg for JsValue);
736
737impl BitAnd for &JsValue {
738    type Output = JsValue;
739
740    /// Applies the binary `&` JS operator on two `JsValue`s.
741    ///
742    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND)
743    #[inline]
744    fn bitand(self, rhs: Self) -> Self::Output {
745        __wbindgen_bit_and(self, rhs)
746    }
747}
748
749forward_deref_binop!(impl BitAnd, bitand for JsValue);
750
751impl BitOr for &JsValue {
752    type Output = JsValue;
753
754    /// Applies the binary `|` JS operator on two `JsValue`s.
755    ///
756    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR)
757    #[inline]
758    fn bitor(self, rhs: Self) -> Self::Output {
759        __wbindgen_bit_or(self, rhs)
760    }
761}
762
763forward_deref_binop!(impl BitOr, bitor for JsValue);
764
765impl BitXor for &JsValue {
766    type Output = JsValue;
767
768    /// Applies the binary `^` JS operator on two `JsValue`s.
769    ///
770    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR)
771    #[inline]
772    fn bitxor(self, rhs: Self) -> Self::Output {
773        __wbindgen_bit_xor(self, rhs)
774    }
775}
776
777forward_deref_binop!(impl BitXor, bitxor for JsValue);
778
779impl Shl for &JsValue {
780    type Output = JsValue;
781
782    /// Applies the binary `<<` JS operator on two `JsValue`s.
783    ///
784    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift)
785    #[inline]
786    fn shl(self, rhs: Self) -> Self::Output {
787        __wbindgen_shl(self, rhs)
788    }
789}
790
791forward_deref_binop!(impl Shl, shl for JsValue);
792
793impl Shr for &JsValue {
794    type Output = JsValue;
795
796    /// Applies the binary `>>` JS operator on two `JsValue`s.
797    ///
798    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)
799    #[inline]
800    fn shr(self, rhs: Self) -> Self::Output {
801        __wbindgen_shr(self, rhs)
802    }
803}
804
805forward_deref_binop!(impl Shr, shr for JsValue);
806
807impl Add for &JsValue {
808    type Output = JsValue;
809
810    /// Applies the binary `+` JS operator on two `JsValue`s.
811    ///
812    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
813    #[inline]
814    fn add(self, rhs: Self) -> Self::Output {
815        __wbindgen_add(self, rhs)
816    }
817}
818
819forward_deref_binop!(impl Add, add for JsValue);
820
821impl Sub for &JsValue {
822    type Output = JsValue;
823
824    /// Applies the binary `-` JS operator on two `JsValue`s.
825    ///
826    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
827    #[inline]
828    fn sub(self, rhs: Self) -> Self::Output {
829        __wbindgen_sub(self, rhs)
830    }
831}
832
833forward_deref_binop!(impl Sub, sub for JsValue);
834
835impl Div for &JsValue {
836    type Output = JsValue;
837
838    /// Applies the binary `/` JS operator on two `JsValue`s.
839    ///
840    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
841    #[inline]
842    fn div(self, rhs: Self) -> Self::Output {
843        __wbindgen_div(self, rhs)
844    }
845}
846
847forward_deref_binop!(impl Div, div for JsValue);
848
849impl Mul for &JsValue {
850    type Output = JsValue;
851
852    /// Applies the binary `*` JS operator on two `JsValue`s.
853    ///
854    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
855    #[inline]
856    fn mul(self, rhs: Self) -> Self::Output {
857        __wbindgen_mul(self, rhs)
858    }
859}
860
861forward_deref_binop!(impl Mul, mul for JsValue);
862
863impl Rem for &JsValue {
864    type Output = JsValue;
865
866    /// Applies the binary `%` JS operator on two `JsValue`s.
867    ///
868    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
869    #[inline]
870    fn rem(self, rhs: Self) -> Self::Output {
871        __wbindgen_rem(self, rhs)
872    }
873}
874
875forward_deref_binop!(impl Rem, rem for JsValue);
876
877impl<'a> From<&'a str> for JsValue {
878    #[inline]
879    fn from(s: &'a str) -> JsValue {
880        JsValue::from_str(s)
881    }
882}
883
884impl<T> From<*mut T> for JsValue {
885    #[inline]
886    fn from(s: *mut T) -> JsValue {
887        JsValue::from(s as usize)
888    }
889}
890
891impl<T> From<*const T> for JsValue {
892    #[inline]
893    fn from(s: *const T) -> JsValue {
894        JsValue::from(s as usize)
895    }
896}
897
898impl<T> From<NonNull<T>> for JsValue {
899    #[inline]
900    fn from(s: NonNull<T>) -> JsValue {
901        JsValue::from(s.as_ptr() as usize)
902    }
903}
904
905impl<'a> From<&'a String> for JsValue {
906    #[inline]
907    fn from(s: &'a String) -> JsValue {
908        JsValue::from_str(s)
909    }
910}
911
912impl From<String> for JsValue {
913    #[inline]
914    fn from(s: String) -> JsValue {
915        JsValue::from_str(&s)
916    }
917}
918
919impl TryFrom<JsValue> for String {
920    type Error = JsValue;
921
922    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
923        match value.as_string() {
924            Some(s) => Ok(s),
925            None => Err(value),
926        }
927    }
928}
929
930impl TryFromJsValue for String {
931    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
932        value.as_string()
933    }
934}
935
936impl From<bool> for JsValue {
937    #[inline]
938    fn from(s: bool) -> JsValue {
939        JsValue::from_bool(s)
940    }
941}
942
943impl TryFromJsValue for bool {
944    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
945        value.as_bool()
946    }
947}
948
949impl TryFromJsValue for char {
950    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
951        let s = value.as_string()?;
952        if s.len() == 1 {
953            Some(s.chars().nth(0).unwrap())
954        } else {
955            None
956        }
957    }
958}
959
960impl<'a, T> From<&'a T> for JsValue
961where
962    T: JsCast,
963{
964    #[inline]
965    fn from(s: &'a T) -> JsValue {
966        s.as_ref().clone()
967    }
968}
969
970impl<T> From<Option<T>> for JsValue
971where
972    JsValue: From<T>,
973{
974    #[inline]
975    fn from(s: Option<T>) -> JsValue {
976        match s {
977            Some(s) => s.into(),
978            None => JsValue::undefined(),
979        }
980    }
981}
982
983// everything is a `JsValue`!
984impl JsCast for JsValue {
985    #[inline]
986    fn instanceof(_val: &JsValue) -> bool {
987        true
988    }
989    #[inline]
990    fn unchecked_from_js(val: JsValue) -> Self {
991        val
992    }
993    #[inline]
994    fn unchecked_from_js_ref(val: &JsValue) -> &Self {
995        val
996    }
997}
998
999impl AsRef<JsValue> for JsValue {
1000    #[inline]
1001    fn as_ref(&self) -> &JsValue {
1002        self
1003    }
1004}
1005
1006impl UpcastFrom<JsValue> for JsValue {}
1007impl<Target: UpcastFrom<JsValue>> UpcastFrom<JsValue> for Option<Target> {}
1008impl<Target: UpcastFrom<JsValue>> UpcastFrom<JsValue> for Nullable<Target> {}
1009
1010// Loosely based on toInt32 in ecma-272 for abi semantics
1011// with restriction that it only applies for numbers
1012fn to_uint_32(v: &JsValue) -> Option<u32> {
1013    v.as_f64().map(|n| {
1014        if n.is_infinite() {
1015            0
1016        } else {
1017            (n as i64) as u32
1018        }
1019    })
1020}
1021
1022macro_rules! integers {
1023    ($($n:ident)*) => ($(
1024        impl PartialEq<$n> for JsValue {
1025            #[inline]
1026            fn eq(&self, other: &$n) -> bool {
1027                self.as_f64() == Some(f64::from(*other))
1028            }
1029        }
1030
1031        impl From<$n> for JsValue {
1032            #[inline]
1033            fn from(n: $n) -> JsValue {
1034                JsValue::from_f64(n.into())
1035            }
1036        }
1037
1038        // Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1039        impl TryFromJsValue for $n {
1040            #[inline]
1041            fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1042                to_uint_32(val).map(|n| n as $n)
1043            }
1044        }
1045    )*)
1046}
1047
1048integers! { i8 u8 i16 u16 i32 u32 }
1049
1050macro_rules! floats {
1051    ($($n:ident)*) => ($(
1052        impl PartialEq<$n> for JsValue {
1053            #[inline]
1054            fn eq(&self, other: &$n) -> bool {
1055                self.as_f64() == Some(f64::from(*other))
1056            }
1057        }
1058
1059        impl From<$n> for JsValue {
1060            #[inline]
1061            fn from(n: $n) -> JsValue {
1062                JsValue::from_f64(n.into())
1063            }
1064        }
1065
1066        impl TryFromJsValue for $n {
1067            #[inline]
1068            fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1069                val.as_f64().map(|n| n as $n)
1070            }
1071        }
1072    )*)
1073}
1074
1075floats! { f32 f64 }
1076
1077macro_rules! big_integers {
1078    ($($n:ident)*) => ($(
1079        impl PartialEq<$n> for JsValue {
1080            #[inline]
1081            fn eq(&self, other: &$n) -> bool {
1082                self == &JsValue::from(*other)
1083            }
1084        }
1085
1086        impl From<$n> for JsValue {
1087            #[inline]
1088            fn from(arg: $n) -> JsValue {
1089                wbg_cast(arg)
1090            }
1091        }
1092
1093        impl TryFrom<JsValue> for $n {
1094            type Error = JsValue;
1095
1096            #[inline]
1097            fn try_from(v: JsValue) -> Result<Self, JsValue> {
1098                Self::try_from_js_value(v)
1099            }
1100        }
1101
1102        impl TryFromJsValue for $n {
1103            #[inline]
1104            fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1105                let as_i64 = __wbindgen_bigint_get_as_i64(&val)?;
1106                // Reinterpret bits; ABI-wise this is safe to do and allows us to avoid
1107                // having separate intrinsics per signed/unsigned types.
1108                let as_self = as_i64 as $n;
1109                // Double-check that we didn't truncate the bigint to 64 bits.
1110                if val == &as_self {
1111                    Some(as_self)
1112                } else {
1113                    None
1114                }
1115            }
1116        }
1117    )*)
1118}
1119
1120big_integers! { i64 u64 }
1121
1122macro_rules! num128 {
1123    ($ty:ty, $hi_ty:ty) => {
1124        impl PartialEq<$ty> for JsValue {
1125            #[inline]
1126            fn eq(&self, other: &$ty) -> bool {
1127                self == &JsValue::from(*other)
1128            }
1129        }
1130
1131        impl From<$ty> for JsValue {
1132            #[inline]
1133            fn from(arg: $ty) -> JsValue {
1134                wbg_cast(arg)
1135            }
1136        }
1137
1138        impl TryFrom<JsValue> for $ty {
1139            type Error = JsValue;
1140
1141            #[inline]
1142            fn try_from(v: JsValue) -> Result<Self, JsValue> {
1143                Self::try_from_js_value(v)
1144            }
1145        }
1146
1147        impl TryFromJsValue for $ty {
1148            // This is a non-standard Wasm bindgen conversion, supported equally
1149            fn try_from_js_value_ref(v: &JsValue) -> Option<$ty> {
1150                // Truncate the bigint to 64 bits, this will give us the lower part.
1151                // The lower part must be interpreted as unsigned in both i128 and u128.
1152                let lo = __wbindgen_bigint_get_as_i64(&v)? as u64;
1153                // Now we know it's a bigint, so we can safely use `>> 64n` without
1154                // worrying about a JS exception on type mismatch.
1155                let hi = v >> JsValue::from(64_u64);
1156                // The high part is the one we want checked against a 64-bit range.
1157                // If it fits, then our original number is in the 128-bit range.
1158                <$hi_ty>::try_from_js_value_ref(&hi).map(|hi| Self::from(hi) << 64 | Self::from(lo))
1159            }
1160        }
1161    };
1162}
1163
1164num128!(i128, i64);
1165
1166num128!(u128, u64);
1167
1168impl TryFromJsValue for () {
1169    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1170        if value.is_undefined() {
1171            Some(())
1172        } else {
1173            None
1174        }
1175    }
1176}
1177
1178impl<T: TryFromJsValue> TryFromJsValue for Option<T> {
1179    const NULLABLE: bool = !T::NULLABLE;
1180
1181    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1182        let none = if T::NULLABLE {
1183            value.is_undefined()
1184        } else {
1185            value.is_null_or_undefined()
1186        };
1187        if none {
1188            Some(None)
1189        } else {
1190            T::try_from_js_value_ref(value).map(Some)
1191        }
1192    }
1193}
1194
1195impl<T: TryFromJsValue> TryFromJsValue for Nullable<T> {
1196    const NULLABLE: bool = true;
1197
1198    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1199        if value.is_null() {
1200            Some(Nullable::Null)
1201        } else {
1202            T::try_from_js_value_ref(value).map(Nullable::Value)
1203        }
1204    }
1205}
1206
1207// Converts a JS `Array` whose elements all convert via `T::try_from_js_value`.
1208// Rejects non-array values and arrays containing any element that fails to
1209// convert. Mirrors the `Array`-shaped representation used by the static ABI
1210// path in `js_value_vector_from_abi`.
1211impl<T: TryFromJsValue> TryFromJsValue for Vec<T> {
1212    fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1213        if !__wbindgen_is_array(value) {
1214            return None;
1215        }
1216        let len = __wbindgen_reflect_get(value, &JsValue::from_str("length")).as_f64()? as u32;
1217        let mut out = Vec::with_capacity(len as usize);
1218        for i in 0..len {
1219            let elem = __wbindgen_reflect_get(value, &JsValue::from_f64(i as f64));
1220            out.push(T::try_from_js_value(elem).ok()?);
1221        }
1222        Some(out)
1223    }
1224}
1225
1226// `usize` and `isize` use the public pointer-sized JS number ABI, which is
1227// `u32`/`i32` on wasm32 and `f64` on wasm64.
1228impl PartialEq<usize> for JsValue {
1229    #[inline]
1230    fn eq(&self, other: &usize) -> bool {
1231        *self == (*other as crate::__rt::WasmWordRepr)
1232    }
1233}
1234
1235impl From<usize> for JsValue {
1236    #[inline]
1237    fn from(n: usize) -> Self {
1238        Self::from(n as crate::__rt::WasmWordRepr)
1239    }
1240}
1241
1242impl PartialEq<isize> for JsValue {
1243    #[inline]
1244    fn eq(&self, other: &isize) -> bool {
1245        *self == (*other as crate::__rt::WasmSignedWordRepr)
1246    }
1247}
1248
1249impl From<isize> for JsValue {
1250    #[inline]
1251    fn from(n: isize) -> Self {
1252        Self::from(n as crate::__rt::WasmSignedWordRepr)
1253    }
1254}
1255
1256// Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1257impl TryFromJsValue for isize {
1258    #[inline]
1259    fn try_from_js_value_ref(val: &JsValue) -> Option<isize> {
1260        val.as_f64().map(|n| n as isize)
1261    }
1262}
1263
1264// Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1265impl TryFromJsValue for usize {
1266    #[inline]
1267    fn try_from_js_value_ref(val: &JsValue) -> Option<usize> {
1268        val.as_f64().map(|n| n as usize)
1269    }
1270}
1271
1272// Intrinsics that are simply JS function bindings and can be self-hosted via the macro.
1273#[wasm_bindgen_macro::wasm_bindgen(wasm_bindgen = crate)]
1274extern "C" {
1275    #[wasm_bindgen(js_namespace = Array, js_name = isArray)]
1276    fn __wbindgen_is_array(v: &JsValue) -> bool;
1277
1278    #[wasm_bindgen(js_namespace = Reflect, js_name = get)]
1279    fn __wbindgen_reflect_get(target: &JsValue, key: &JsValue) -> JsValue;
1280
1281    #[wasm_bindgen(js_name = BigInt)]
1282    fn __wbindgen_bigint_from_str(s: &str) -> JsValue;
1283
1284    #[wasm_bindgen(js_name = Symbol)]
1285    fn __wbindgen_symbol_new(description: Option<&str>) -> JsValue;
1286
1287    #[wasm_bindgen(js_name = Error)]
1288    fn __wbindgen_error_new(msg: &str) -> JsValue;
1289
1290    #[wasm_bindgen(js_namespace = JSON, js_name = parse)]
1291    fn __wbindgen_json_parse(json: String) -> JsValue;
1292
1293    #[wasm_bindgen(js_namespace = JSON, js_name = stringify)]
1294    fn __wbindgen_json_serialize(v: &JsValue) -> Option<String>;
1295
1296    #[wasm_bindgen(js_name = Number)]
1297    fn __wbindgen_as_number(v: &JsValue) -> f64;
1298}
1299
1300// Intrinsics which are handled by cli-support but for which we can use
1301// standard wasm-bindgen ABI conversions.
1302#[wasm_bindgen_macro::wasm_bindgen(wasm_bindgen = crate, raw_module = "__wbindgen_placeholder__")]
1303extern "C" {
1304    #[cfg(not(wbg_reference_types))]
1305    fn __wbindgen_externref_heap_live_count() -> u32;
1306
1307    fn __wbindgen_is_null(js: &JsValue) -> bool;
1308    fn __wbindgen_is_undefined(js: &JsValue) -> bool;
1309    fn __wbindgen_is_null_or_undefined(js: &JsValue) -> bool;
1310    fn __wbindgen_is_symbol(js: &JsValue) -> bool;
1311    fn __wbindgen_is_object(js: &JsValue) -> bool;
1312    fn __wbindgen_is_function(js: &JsValue) -> bool;
1313    fn __wbindgen_is_string(js: &JsValue) -> bool;
1314    fn __wbindgen_is_bigint(js: &JsValue) -> bool;
1315    fn __wbindgen_typeof(js: &JsValue) -> JsValue;
1316
1317    fn __wbindgen_in(prop: &JsValue, obj: &JsValue) -> bool;
1318
1319    fn __wbindgen_is_falsy(js: &JsValue) -> bool;
1320    fn __wbindgen_try_into_number(js: &JsValue) -> JsValue;
1321    fn __wbindgen_neg(js: &JsValue) -> JsValue;
1322    fn __wbindgen_bit_and(a: &JsValue, b: &JsValue) -> JsValue;
1323    fn __wbindgen_bit_or(a: &JsValue, b: &JsValue) -> JsValue;
1324    fn __wbindgen_bit_xor(a: &JsValue, b: &JsValue) -> JsValue;
1325    fn __wbindgen_bit_not(js: &JsValue) -> JsValue;
1326    fn __wbindgen_shl(a: &JsValue, b: &JsValue) -> JsValue;
1327    fn __wbindgen_shr(a: &JsValue, b: &JsValue) -> JsValue;
1328    fn __wbindgen_unsigned_shr(a: &JsValue, b: &JsValue) -> u32;
1329    fn __wbindgen_add(a: &JsValue, b: &JsValue) -> JsValue;
1330    fn __wbindgen_sub(a: &JsValue, b: &JsValue) -> JsValue;
1331    fn __wbindgen_div(a: &JsValue, b: &JsValue) -> JsValue;
1332    fn __wbindgen_checked_div(a: &JsValue, b: &JsValue) -> JsValue;
1333    fn __wbindgen_mul(a: &JsValue, b: &JsValue) -> JsValue;
1334    fn __wbindgen_rem(a: &JsValue, b: &JsValue) -> JsValue;
1335    fn __wbindgen_pow(a: &JsValue, b: &JsValue) -> JsValue;
1336    fn __wbindgen_lt(a: &JsValue, b: &JsValue) -> bool;
1337    fn __wbindgen_le(a: &JsValue, b: &JsValue) -> bool;
1338    fn __wbindgen_ge(a: &JsValue, b: &JsValue) -> bool;
1339    fn __wbindgen_gt(a: &JsValue, b: &JsValue) -> bool;
1340
1341    fn __wbindgen_number_get(js: &JsValue) -> Option<f64>;
1342    fn __wbindgen_boolean_get(js: &JsValue) -> Option<bool>;
1343    fn __wbindgen_string_get(js: &JsValue) -> Option<String>;
1344    fn __wbindgen_string_from_utf8_lossy(bytes: &[u8]) -> JsValue;
1345    fn __wbindgen_bigint_get_as_i64(js: &JsValue) -> Option<i64>;
1346
1347    fn __wbindgen_debug_string(js: &JsValue) -> String;
1348
1349    fn __wbindgen_throw(msg: &str) /* -> ! */;
1350    fn __wbindgen_rethrow(js: JsValue) /* -> ! */;
1351
1352    fn __wbindgen_jsval_eq(a: &JsValue, b: &JsValue) -> bool;
1353    fn __wbindgen_jsval_loose_eq(a: &JsValue, b: &JsValue) -> bool;
1354
1355    fn __wbindgen_copy_to_typed_array(data: &[u8], js: &JsValue);
1356
1357    fn __wbindgen_init_externref_table();
1358
1359    fn __wbindgen_exports() -> JsValue;
1360    fn __wbindgen_memory() -> JsValue;
1361    fn __wbindgen_module() -> JsValue;
1362    fn __wbindgen_instance() -> JsValue;
1363    fn __wbindgen_function_table() -> JsValue;
1364
1365    fn __wbindgen_reinit();
1366}
1367
1368// Intrinsics that have to use raw imports because they're matched by other
1369// parts of the transform codebase instead of just generating JS.
1370externs! {
1371    #[link(wasm_import_module = "__wbindgen_placeholder__")]
1372    extern "C" {
1373        fn __wbindgen_object_clone_ref(idx: u32) -> u32;
1374        fn __wbindgen_object_drop_ref(idx: u32) -> ();
1375
1376        fn __wbindgen_describe(v: u32) -> ();
1377        // Marker terminating a descriptor function, signaling to the CLI that
1378        // the parent function is a monomorphisation to be discovered,
1379        // interpreted, and rewritten to a manufactured JS binding. The
1380        // descriptor stream preceding this call carries a length-prefixed
1381        // `shim` key followed by the concrete `FUNCTION` signature for this
1382        // monomorphisation. A non-empty key identifies which generic-import AST
1383        // entry supplies the JS binding metadata; an empty key marks a `wbg_cast`
1384        // identity adapter (see `__rt::wbg_cast`).
1385        fn __wbindgen_describe_generic_import(func: *const (), prims: *const ()) -> *const ();
1386    }
1387}
1388
1389/// One past the last fixed `externref` table slot: the reserved constants
1390/// and the `static_string` constants. Those slots are shared by every
1391/// `JsValue` with that index, so they are never dropped and clone for free.
1392#[inline]
1393fn externref_statics_end() -> u32 {
1394    #[cfg(wbg_reference_types)]
1395    return externref::statics_end();
1396    #[cfg(not(wbg_reference_types))]
1397    __rt::JSIDX_RESERVED
1398}
1399
1400impl Clone for JsValue {
1401    #[inline]
1402    fn clone(&self) -> JsValue {
1403        if (__rt::JSIDX_OFFSET..externref_statics_end()).contains(&self.idx) {
1404            JsValue::_new(self.idx)
1405        } else {
1406            JsValue::_new(unsafe { __wbindgen_object_clone_ref(self.idx) })
1407        }
1408    }
1409}
1410
1411impl core::fmt::Debug for JsValue {
1412    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1413        write!(f, "JsValue({})", self.as_debug_string())
1414    }
1415}
1416
1417impl Drop for JsValue {
1418    #[inline]
1419    fn drop(&mut self) {
1420        unsafe {
1421            // We definitely should never drop anything in the stack area
1422            debug_assert!(
1423                self.idx >= __rt::JSIDX_OFFSET,
1424                "free of stack slot {}",
1425                self.idx
1426            );
1427
1428            // Otherwise if we're not dropping one of our fixed values,
1429            // actually call the intrinsic. See #1054 for eventually removing
1430            // this branch.
1431            if self.idx >= externref_statics_end() {
1432                __wbindgen_object_drop_ref(self.idx);
1433            }
1434        }
1435    }
1436}
1437
1438impl Default for JsValue {
1439    fn default() -> Self {
1440        Self::UNDEFINED
1441    }
1442}
1443
1444/// Wrapper type for imported statics.
1445///
1446/// This type is used whenever a `static` is imported from a JS module, for
1447/// example this import:
1448///
1449/// ```ignore
1450/// #[wasm_bindgen]
1451/// extern "C" {
1452///     static console: JsValue;
1453/// }
1454/// ```
1455///
1456/// will generate in Rust a value that looks like:
1457///
1458/// ```ignore
1459/// static console: JsStatic<JsValue> = ...;
1460/// ```
1461///
1462/// This type implements `Deref` to the inner type so it's typically used as if
1463/// it were `&T`.
1464#[cfg(feature = "std")]
1465#[deprecated = "use with `#[wasm_bindgen(thread_local_v2)]` instead"]
1466pub struct JsStatic<T: 'static> {
1467    #[doc(hidden)]
1468    pub __inner: &'static std::thread::LocalKey<T>,
1469}
1470
1471#[cfg(feature = "std")]
1472#[allow(deprecated)]
1473#[cfg(not(target_feature = "atomics"))]
1474impl<T: crate::convert::FromWasmAbi + 'static> Deref for JsStatic<T> {
1475    type Target = T;
1476    fn deref(&self) -> &T {
1477        unsafe { self.__inner.with(|ptr| &*(ptr as *const T)) }
1478    }
1479}
1480
1481/// Wrapper type for imported statics.
1482///
1483/// This type is used whenever a `static` is imported from a JS module, for
1484/// example this import:
1485///
1486/// ```ignore
1487/// #[wasm_bindgen]
1488/// extern "C" {
1489///     #[wasm_bindgen(thread_local_v2)]
1490///     static console: JsValue;
1491/// }
1492/// ```
1493///
1494/// will generate in Rust a value that looks like:
1495///
1496/// ```ignore
1497/// static console: JsThreadLocal<JsValue> = ...;
1498/// ```
1499pub struct JsThreadLocal<T: 'static> {
1500    #[doc(hidden)]
1501    #[cfg(not(target_feature = "atomics"))]
1502    pub __inner: &'static __rt::LazyCell<T>,
1503    #[doc(hidden)]
1504    #[cfg(target_feature = "atomics")]
1505    pub __inner: fn() -> *const T,
1506}
1507
1508impl<T> JsThreadLocal<T> {
1509    pub fn with<F, R>(&'static self, f: F) -> R
1510    where
1511        F: FnOnce(&T) -> R,
1512    {
1513        #[cfg(not(target_feature = "atomics"))]
1514        return f(self.__inner);
1515        #[cfg(target_feature = "atomics")]
1516        f(unsafe { &*(self.__inner)() })
1517    }
1518}
1519
1520#[cold]
1521#[inline(never)]
1522#[deprecated(note = "renamed to `throw_str`")]
1523#[doc(hidden)]
1524pub fn throw(s: &str) -> ! {
1525    throw_str(s)
1526}
1527
1528/// Throws a JS exception.
1529///
1530/// This function will throw a JS exception with the message provided. The
1531/// function will not return as the Wasm stack will be popped when the exception
1532/// is thrown.
1533///
1534/// Note that it is very easy to leak memory with this function because this
1535/// function, unlike `panic!` on other platforms, **will not run destructors**.
1536/// It's recommended to return a `Result` where possible to avoid the worry of
1537/// leaks.
1538///
1539/// If you need destructors to run, consider using `panic!` when building with
1540/// `-Cpanic=unwind`. If the `std` feature is used panics will be caught at the
1541/// JavaScript boundary and converted to JavaScript exceptions.
1542#[cold]
1543#[inline(never)]
1544pub fn throw_str(s: &str) -> ! {
1545    __wbindgen_throw(s);
1546    unsafe { core::hint::unreachable_unchecked() }
1547}
1548
1549/// Rethrow a JS exception
1550///
1551/// This function will throw a JS exception with the JS value provided. This
1552/// function will not return and the Wasm stack will be popped until the point
1553/// of entry of Wasm itself.
1554///
1555/// Note that it is very easy to leak memory with this function because this
1556/// function, unlike `panic!` on other platforms, **will not run destructors**.
1557/// It's recommended to return a `Result` where possible to avoid the worry of
1558/// leaks.
1559///
1560/// If you need destructors to run, consider using `panic!` when building with
1561/// `-Cpanic=unwind`. If the `std` feature is used panics will be caught at the
1562/// JavaScript boundary and converted to JavaScript exceptions.
1563#[cold]
1564#[inline(never)]
1565pub fn throw_val(s: JsValue) -> ! {
1566    __wbindgen_rethrow(s);
1567    unsafe { core::hint::unreachable_unchecked() }
1568}
1569
1570/// Get the count of live `externref`s / `JsValue`s in `wasm-bindgen`'s heap.
1571///
1572/// ## Usage
1573///
1574/// This is intended for debugging and writing tests.
1575///
1576/// To write a test that asserts against unnecessarily keeping `anref`s /
1577/// `JsValue`s alive:
1578///
1579/// * get an initial live count,
1580///
1581/// * perform some series of operations or function calls that should clean up
1582///   after themselves, and should not keep holding onto `externref`s / `JsValue`s
1583///   after completion,
1584///
1585/// * get the final live count,
1586///
1587/// * and assert that the initial and final counts are the same.
1588///
1589/// ## What is Counted
1590///
1591/// Note that this only counts the *owned* `externref`s / `JsValue`s that end up in
1592/// `wasm-bindgen`'s heap. It does not count borrowed `externref`s / `JsValue`s
1593/// that are on its stack.
1594///
1595/// For example, these `JsValue`s are accounted for:
1596///
1597/// ```ignore
1598/// #[wasm_bindgen]
1599/// pub fn my_function(this_is_counted: JsValue) {
1600///     let also_counted = JsValue::from_str("hi");
1601///     assert!(wasm_bindgen::externref_heap_live_count() >= 2);
1602/// }
1603/// ```
1604///
1605/// While this borrowed `JsValue` ends up on the stack, not the heap, and
1606/// therefore is not accounted for:
1607///
1608/// ```ignore
1609/// #[wasm_bindgen]
1610/// pub fn my_other_function(this_is_not_counted: &JsValue) {
1611///     // ...
1612/// }
1613/// ```
1614pub fn externref_heap_live_count() -> u32 {
1615    __wbindgen_externref_heap_live_count()
1616}
1617
1618#[doc(hidden)]
1619pub fn anyref_heap_live_count() -> u32 {
1620    externref_heap_live_count()
1621}
1622
1623/// An extension trait for `Option<T>` and `Result<T, E>` for unwrapping the `T`
1624/// value, or throwing a JS error if it is not available.
1625///
1626/// These methods should have a smaller code size footprint than the normal
1627/// `Option::unwrap` and `Option::expect` methods, but they are specific to
1628/// working with Wasm and JS.
1629///
1630/// On non-wasm32 targets, defaults to the normal unwrap/expect calls.
1631///
1632/// # Example
1633///
1634/// ```
1635/// use wasm_bindgen::prelude::*;
1636///
1637/// // If the value is `Option::Some` or `Result::Ok`, then we just get the
1638/// // contained `T` value.
1639/// let x = Some(42);
1640/// assert_eq!(x.unwrap_throw(), 42);
1641///
1642/// let y: Option<i32> = None;
1643///
1644/// // This call would throw an error to JS!
1645/// //
1646/// //     y.unwrap_throw()
1647/// //
1648/// // And this call would throw an error to JS with a custom error message!
1649/// //
1650/// //     y.expect_throw("woopsie daisy!")
1651/// ```
1652pub trait UnwrapThrowExt<T>: Sized {
1653    /// Unwrap this `Option` or `Result`, but instead of panicking on failure,
1654    /// throw an exception to JavaScript.
1655    #[cfg_attr(
1656        any(
1657            debug_assertions,
1658            not(all(target_family = "wasm", not(target_os = "wasi")))
1659        ),
1660        track_caller
1661    )]
1662    fn unwrap_throw(self) -> T {
1663        if cfg!(all(
1664            debug_assertions,
1665            all(target_family = "wasm", not(target_os = "wasi"))
1666        )) {
1667            let loc = core::panic::Location::caller();
1668            let msg = alloc::format!(
1669                "called `{}::unwrap_throw()` ({}:{}:{})",
1670                core::any::type_name::<Self>(),
1671                loc.file(),
1672                loc.line(),
1673                loc.column()
1674            );
1675            self.expect_throw(&msg)
1676        } else {
1677            self.expect_throw("called `unwrap_throw()`")
1678        }
1679    }
1680
1681    /// Unwrap this container's `T` value, or throw an error to JS with the
1682    /// given message if the `T` value is unavailable (e.g. an `Option<T>` is
1683    /// `None`).
1684    #[cfg_attr(
1685        any(
1686            debug_assertions,
1687            not(all(target_family = "wasm", not(target_os = "wasi")))
1688        ),
1689        track_caller
1690    )]
1691    fn expect_throw(self, message: &str) -> T;
1692}
1693
1694impl<T> UnwrapThrowExt<T> for Option<T> {
1695    fn unwrap_throw(self) -> T {
1696        const MSG: &str = "called `Option::unwrap_throw()` on a `None` value";
1697
1698        if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1699            if let Some(val) = self {
1700                val
1701            } else if cfg!(debug_assertions) {
1702                let loc = core::panic::Location::caller();
1703                let msg = alloc::format!("{MSG} ({}:{}:{})", loc.file(), loc.line(), loc.column(),);
1704
1705                throw_str(&msg)
1706            } else {
1707                throw_str(MSG)
1708            }
1709        } else {
1710            self.expect(MSG)
1711        }
1712    }
1713
1714    fn expect_throw(self, message: &str) -> T {
1715        if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1716            if let Some(val) = self {
1717                val
1718            } else if cfg!(debug_assertions) {
1719                let loc = core::panic::Location::caller();
1720                let msg =
1721                    alloc::format!("{message} ({}:{}:{})", loc.file(), loc.line(), loc.column(),);
1722
1723                throw_str(&msg)
1724            } else {
1725                throw_str(message)
1726            }
1727        } else {
1728            self.expect(message)
1729        }
1730    }
1731}
1732
1733impl<T, E> UnwrapThrowExt<T> for Result<T, E>
1734where
1735    E: core::fmt::Debug,
1736{
1737    fn unwrap_throw(self) -> T {
1738        const MSG: &str = "called `Result::unwrap_throw()` on an `Err` value";
1739
1740        if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1741            match self {
1742                Ok(val) => val,
1743                Err(err) => {
1744                    if cfg!(debug_assertions) {
1745                        let loc = core::panic::Location::caller();
1746                        let msg = alloc::format!(
1747                            "{MSG} ({}:{}:{}): {err:?}",
1748                            loc.file(),
1749                            loc.line(),
1750                            loc.column(),
1751                        );
1752
1753                        throw_str(&msg)
1754                    } else {
1755                        throw_str(MSG)
1756                    }
1757                }
1758            }
1759        } else {
1760            self.expect(MSG)
1761        }
1762    }
1763
1764    fn expect_throw(self, message: &str) -> T {
1765        if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1766            match self {
1767                Ok(val) => val,
1768                Err(err) => {
1769                    if cfg!(debug_assertions) {
1770                        let loc = core::panic::Location::caller();
1771                        let msg = alloc::format!(
1772                            "{message} ({}:{}:{}): {err:?}",
1773                            loc.file(),
1774                            loc.line(),
1775                            loc.column(),
1776                        );
1777
1778                        throw_str(&msg)
1779                    } else {
1780                        throw_str(message)
1781                    }
1782                }
1783            }
1784        } else {
1785            self.expect(message)
1786        }
1787    }
1788}
1789
1790/// Returns a handle to this Wasm instance's `WebAssembly.Module`.
1791/// This is only available when the final Wasm app is built with
1792/// `--target no-modules`, `--target web`, `--target deno` or `--target nodejs`.
1793/// It is unavailable for `--target bundler`.
1794pub fn module() -> JsValue {
1795    __wbindgen_module()
1796}
1797
1798/// Returns a handle to this Wasm instance's `WebAssembly.Instance`.
1799/// This is only available when the final Wasm app is built with
1800/// `--target no-modules`, `--target web`, `--target deno` or `--target nodejs`.
1801/// It is unavailable for `--target bundler`.
1802pub fn instance() -> JsValue {
1803    __wbindgen_instance()
1804}
1805
1806// TODO: deprecate next major
1807/// Returns a handle to this Wasm instance's `WebAssembly.Instance.prototype.exports`
1808pub fn exports() -> JsValue {
1809    __wbindgen_exports()
1810}
1811
1812/// Returns a handle to this Wasm instance's `WebAssembly.Memory`
1813pub fn memory() -> JsValue {
1814    __wbindgen_memory()
1815}
1816
1817/// Returns a handle to this Wasm instance's `WebAssembly.Table` which is the
1818/// indirect function table used by Rust
1819pub fn function_table() -> JsValue {
1820    __wbindgen_function_table()
1821}
1822
1823/// A wrapper type around slices and vectors for binding the `Uint8ClampedArray`
1824/// array in JS.
1825///
1826/// If you need to invoke a JS API which must take `Uint8ClampedArray` array,
1827/// then you can define it as taking one of these types:
1828///
1829/// * `Clamped<&[u8]>`
1830/// * `Clamped<&mut [u8]>`
1831/// * `Clamped<Vec<u8>>`
1832///
1833/// All of these types will show up as `Uint8ClampedArray` in JS and will have
1834/// different forms of ownership in Rust.
1835#[derive(Copy, Clone, PartialEq, Debug, Eq)]
1836pub struct Clamped<T>(pub T);
1837
1838impl<T> Deref for Clamped<T> {
1839    type Target = T;
1840
1841    fn deref(&self) -> &T {
1842        &self.0
1843    }
1844}
1845
1846impl<T> DerefMut for Clamped<T> {
1847    fn deref_mut(&mut self) -> &mut T {
1848        &mut self.0
1849    }
1850}
1851
1852/// Convenience type for use on exported `fn() -> Result<T, JsError>` functions, where you wish to
1853/// throw a JavaScript `Error` object.
1854///
1855/// You can get wasm_bindgen to throw basic errors by simply returning
1856/// `Err(JsError::new("message"))` from such a function.
1857///
1858/// For more complex error handling, `JsError` implements `From<T> where T: std::error::Error` by
1859/// converting it to a string, so you can use it with `?`. Many Rust error types already do this,
1860/// and you can use [`thiserror`](https://crates.io/crates/thiserror) to derive Display
1861/// implementations easily or use any number of boxed error types that implement it already.
1862///
1863///
1864/// To allow JavaScript code to catch only your errors, you may wish to add a subclass of `Error`
1865/// in a JS module, and then implement `Into<JsValue>` directly on a type and instantiate that
1866/// subclass. In that case, you would not need `JsError` at all.
1867///
1868/// ### Basic example
1869///
1870/// ```rust,no_run
1871/// use wasm_bindgen::prelude::*;
1872///
1873/// #[wasm_bindgen]
1874/// pub fn throwing_function() -> Result<(), JsError> {
1875///     Err(JsError::new("message"))
1876/// }
1877/// ```
1878///
1879/// ### Complex Example
1880///
1881/// ```rust,no_run
1882/// use wasm_bindgen::prelude::*;
1883///
1884/// #[derive(Debug, Clone)]
1885/// enum MyErrorType {
1886///     SomeError,
1887/// }
1888///
1889/// use core::fmt;
1890/// impl std::error::Error for MyErrorType {}
1891/// impl fmt::Display for MyErrorType {
1892///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1893///         write!(f, "display implementation becomes the error message")
1894///     }
1895/// }
1896///
1897/// fn internal_api() -> Result<(), MyErrorType> {
1898///     Err(MyErrorType::SomeError)
1899/// }
1900///
1901/// #[wasm_bindgen]
1902/// pub fn throwing_function() -> Result<(), JsError> {
1903///     internal_api()?;
1904///     Ok(())
1905/// }
1906///
1907/// ```
1908#[derive(Clone, Debug)]
1909#[repr(transparent)]
1910pub struct JsError {
1911    value: JsValue,
1912}
1913
1914impl JsError {
1915    /// Construct a JavaScript `Error` object with a string message
1916    #[inline]
1917    pub fn new(s: &str) -> JsError {
1918        Self {
1919            value: __wbindgen_error_new(s),
1920        }
1921    }
1922}
1923
1924impl<E> From<E> for JsError
1925where
1926    E: core::error::Error,
1927{
1928    fn from(error: E) -> Self {
1929        use alloc::string::ToString;
1930
1931        JsError::new(&error.to_string())
1932    }
1933}
1934
1935impl From<JsError> for JsValue {
1936    fn from(error: JsError) -> Self {
1937        error.value
1938    }
1939}
1940
1941impl<T: VectorIntoWasmAbi> From<Box<[T]>> for JsValue {
1942    fn from(vector: Box<[T]>) -> Self {
1943        wbg_cast(vector)
1944    }
1945}
1946
1947impl<T: VectorIntoWasmAbi> From<Clamped<Box<[T]>>> for JsValue {
1948    fn from(vector: Clamped<Box<[T]>>) -> Self {
1949        wbg_cast(vector)
1950    }
1951}
1952
1953impl<T: VectorIntoWasmAbi> From<Vec<T>> for JsValue {
1954    fn from(vector: Vec<T>) -> Self {
1955        JsValue::from(vector.into_boxed_slice())
1956    }
1957}
1958
1959impl<T: VectorIntoWasmAbi> From<Clamped<Vec<T>>> for JsValue {
1960    fn from(vector: Clamped<Vec<T>>) -> Self {
1961        JsValue::from(Clamped(vector.0.into_boxed_slice()))
1962    }
1963}