Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+506
View File
@@ -0,0 +1,506 @@
use alloc::boxed::Box;
use core::mem;
use core::panic::AssertUnwindSafe;
use crate::__rt::marker::ErasableGeneric;
use crate::__rt::maybe_catch_unwind;
use crate::__rt::WasmWord;
use crate::closure::{
Closure, IntoWasmClosure, IntoWasmClosureRef, IntoWasmClosureRefMut, ScopedClosure,
WasmClosure, WasmClosureFnOnce, WasmClosureFnOnceAbort,
};
use crate::convert::slices::WasmSlice;
use crate::convert::traits::UpcastFrom;
use crate::convert::RefFromWasmAbi;
use crate::convert::{FromWasmAbi, IntoWasmAbi, ReturnWasmAbi, WasmAbi, WasmRet};
use crate::describe::{inform, WasmDescribe, FUNCTION};
use crate::sys::Undefined;
use crate::throw_str;
use crate::JsValue;
use crate::UnwrapThrowExt;
macro_rules! closures {
// Unwind safe passing
([$($maybe_unwind_safe:tt)*] $($rest:tt)*) => {
closures!(@process [$($maybe_unwind_safe)*] $($rest)*);
};
// One-arity recurse
(@process [$($unwind_safe:tt)*] ($($var:ident $arg1:ident $arg2:ident $arg3:ident $arg4:ident)*) $($rest:tt)*) => {
closures!(@impl_for_args ($($var),*) FromWasmAbi [$($unwind_safe)*] $($var::from_abi($var) => $var $arg1 $arg2 $arg3 $arg4)*);
closures!(@process [$($unwind_safe)*] $($rest)*);
};
// Base case
(@process [$($unwind_safe:tt)*]) => {};
// A counter helper to count number of arguments.
(@count_one $ty:ty) => (1);
(@describe ( $($ty:ty),* )) => {
// Needs to be a constant so that interpreter doesn't crash on
// unsupported operations in debug mode.
const ARG_COUNT: u32 = 0 $(+ closures!(@count_one $ty))*;
inform(ARG_COUNT);
$(<$ty>::describe();)*
};
// This silly helper is because by default Rust infers `|var_with_ref_type| ...` closure
// as `impl Fn(&'outer_lifetime A)` instead of `impl for<'temp_lifetime> Fn(&'temp_lifetime A)`
// while `|var_with_ref_type: &A|` makes it use the higher-order generic as expected.
(@closure ($($ty:ty),*) $($var:ident)* $body:block) => (move |$($var: $ty),*| $body);
(@impl_for_fn $is_mut:literal [$($mut:ident)?] $Fn:ident $FnArgs:tt $FromWasmAbi:ident $($var_expr:expr => $var:ident $arg1:ident $arg2:ident $arg3:ident $arg4:ident)*) => (const _: () = {
impl<$($var,)* R> IntoWasmAbi for &'_ $($mut)? (dyn $Fn $FnArgs -> R + '_)
where
Self: WasmDescribe,
{
type Abi = WasmSlice;
fn into_abi(self) -> WasmSlice {
unsafe {
let (a, b): (usize, usize) = mem::transmute(self);
WasmSlice::from_usize(a, b)
}
}
}
unsafe impl<'a, $($var,)* R> ErasableGeneric for &'a $($mut)? (dyn $Fn $FnArgs -> R + 'a)
where
$($var: ErasableGeneric,)*
R: ErasableGeneric
{
type Repr = &'static (dyn $Fn ($(<$var as ErasableGeneric>::Repr,)*) -> <R as ErasableGeneric>::Repr + 'static);
}
// Invoke shim for closures. The const generic `UNWIND_SAFE` controls
// whether panics are caught and converted to JS exceptions (`true`) or
// left to unwind/abort (`false`). When `panic=unwind` is not available,
// `UNWIND_SAFE` has no effect — panics always abort.
#[allow(non_snake_case)]
unsafe extern "C-unwind" fn invoke<$($var: $FromWasmAbi,)* R: ReturnWasmAbi, const UNWIND_SAFE: bool>(
a: WasmWord,
b: WasmWord,
$(
$arg1: <$var::Abi as WasmAbi>::Prim1,
$arg2: <$var::Abi as WasmAbi>::Prim2,
$arg3: <$var::Abi as WasmAbi>::Prim3,
$arg4: <$var::Abi as WasmAbi>::Prim4,
)*
) -> WasmRet<R::Abi> {
if a.is_zero() {
throw_str("closure invoked recursively or after being dropped");
}
let ret = {
let f: & $($mut)? dyn $Fn $FnArgs -> R =
mem::transmute((a.into_usize(), b.into_usize()));
$(
let $var = $var::Abi::join($arg1, $arg2, $arg3, $arg4);
)*
if UNWIND_SAFE {
maybe_catch_unwind(AssertUnwindSafe(|| f($($var_expr),*)))
} else {
f($($var_expr),*)
}
};
ret.return_abi().into()
}
#[allow(clippy::fn_to_numeric_cast)]
impl<$($var,)* R> WasmDescribe for dyn $Fn $FnArgs -> R + '_
where
$($var: $FromWasmAbi,)*
R: ReturnWasmAbi,
{
#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
fn describe() {
// Raw &dyn Fn/&dyn FnMut passed as arguments use the catching
// invoke shim by default, matching the previous runtime behavior.
<Self as WasmClosure>::describe_invoke::<true>();
}
}
unsafe impl<'__closure, $($var,)* R> WasmClosure for dyn $Fn $FnArgs -> R + '__closure
where
$($var: $FromWasmAbi,)*
R: ReturnWasmAbi,
{
const IS_MUT: bool = $is_mut;
type Static = dyn $Fn $FnArgs -> R;
type AsMut = dyn FnMut $FnArgs -> R + '__closure;
#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
fn describe_invoke<const UNWIND_SAFE: bool>() {
inform(FUNCTION);
inform(invoke::<$($var,)* R, UNWIND_SAFE> as *const () as usize as u32);
closures!(@describe $FnArgs);
R::describe();
R::describe();
}
}
impl<T, $($var,)* R> IntoWasmClosure<dyn $Fn $FnArgs -> R> for T
where
T: 'static + $Fn $FnArgs -> R,
{
fn unsize(self: Box<Self>) -> Box<dyn $Fn $FnArgs -> R> { self }
}
};);
// IntoWasmClosureRef is only implemented for Fn, not FnMut.
// IntoWasmClosureRefMut is implemented for FnMut.
// Since Fn: FnMut, any Fn closure can be used as FnMut, so this covers all cases.
(@impl_unsize_closure_ref $FnArgs:tt $FromWasmAbi:ident $($var_expr:expr => $var:ident $arg1:ident $arg2:ident $arg3:ident $arg4:ident)*) => (
impl<'a, T: 'a, $($var: 'a + $FromWasmAbi,)* R: 'a + ReturnWasmAbi> IntoWasmClosureRef<dyn Fn $FnArgs -> R + 'a> for T
where
T: Fn $FnArgs -> R,
{
fn unsize_closure_ref(&self) -> &(dyn Fn $FnArgs -> R + 'a) { self }
}
impl<'a, T: 'a, $($var: 'a + $FromWasmAbi,)* R: 'a + ReturnWasmAbi> IntoWasmClosureRefMut<dyn FnMut $FnArgs -> R + 'a> for T
where
T: FnMut $FnArgs -> R,
{
fn unsize_closure_ref(&mut self) -> &mut (dyn FnMut $FnArgs -> R + 'a) { self }
}
);
(@impl_for_args $FnArgs:tt $FromWasmAbi:ident [$($maybe_unwind_safe:tt)*] $($var_expr:expr => $var:ident $arg1:ident $arg2:ident $arg3:ident $arg4:ident)*) => {
closures!(@impl_for_fn false [] Fn $FnArgs $FromWasmAbi $($var_expr => $var $arg1 $arg2 $arg3 $arg4)*);
closures!(@impl_for_fn true [mut] FnMut $FnArgs $FromWasmAbi $($var_expr => $var $arg1 $arg2 $arg3 $arg4)*);
closures!(@impl_unsize_closure_ref $FnArgs $FromWasmAbi $($var_expr => $var $arg1 $arg2 $arg3 $arg4)*);
// The memory safety here in these implementations below is a bit tricky. We
// want to be able to drop the `Closure` object from within the invocation of a
// `Closure` for cases like promises. That means that while it's running we
// might drop the `Closure`, but that shouldn't invalidate the environment yet.
//
// Instead what we do is to wrap closures in `Rc` variables. The main `Closure`
// has a strong reference count which keeps the trait object alive. Each
// invocation of a closure then *also* clones this and gets a new reference
// count. When the closure returns it will release the reference count.
//
// This means that if the main `Closure` is dropped while it's being invoked
// then destruction is deferred until execution returns. Otherwise it'll
// deallocate data immediately.
#[allow(non_snake_case, unused_parens)]
impl<T, $($var,)* R> WasmClosureFnOnce<dyn FnMut $FnArgs -> R, $FnArgs, R> for T
where
T: 'static + (FnOnce $FnArgs -> R),
$($var: $FromWasmAbi + 'static,)*
R: ReturnWasmAbi + 'static,
$($maybe_unwind_safe)*
{
fn into_fn_mut(self) -> Box<dyn FnMut $FnArgs -> R> {
let mut me = Some(self);
Box::new(move |$($var),*| {
let me = me.take().expect_throw("FnOnce called more than once");
me($($var),*)
})
}
fn into_js_function(self) -> JsValue {
use alloc::rc::Rc;
use crate::__rt::WasmRefCell;
let rc1 = Rc::new(WasmRefCell::new(None));
let rc2 = rc1.clone();
let closure = Closure::once(closures!(@closure $FnArgs $($var)* {
let result = self($($var),*);
// And then drop the `Rc` holding this function's `Closure`
// alive.
debug_assert_eq!(Rc::strong_count(&rc2), 1);
let option_closure = rc2.borrow_mut().take();
debug_assert!(option_closure.is_some());
drop(option_closure);
result
}));
let js_val = closure.as_ref().clone();
*rc1.borrow_mut() = Some(closure);
debug_assert_eq!(Rc::strong_count(&rc1), 2);
drop(rc1);
js_val
}
}
#[allow(non_snake_case, unused_parens)]
impl<T, $($var,)* R> WasmClosureFnOnceAbort<dyn FnMut $FnArgs -> R, $FnArgs, R> for T
where
T: 'static + (FnOnce $FnArgs -> R),
$($var: $FromWasmAbi + 'static,)*
R: ReturnWasmAbi + 'static,
{
fn into_fn_mut(self) -> Box<dyn FnMut $FnArgs -> R> {
let mut me = Some(self);
Box::new(move |$($var),*| {
let me = me.take().expect_throw("FnOnce called more than once");
me($($var),*)
})
}
fn into_js_function(self) -> JsValue {
use alloc::rc::Rc;
use crate::__rt::WasmRefCell;
let rc1 = Rc::new(WasmRefCell::new(None));
let rc2 = rc1.clone();
// TODO: Unwind safety for FnOnce
let closure = Closure::once_aborting(closures!(@closure $FnArgs $($var)* {
let result = self($($var),*);
// And then drop the `Rc` holding this function's `Closure`
// alive.
debug_assert_eq!(Rc::strong_count(&rc2), 1);
let option_closure = rc2.borrow_mut().take();
debug_assert!(option_closure.is_some());
drop(option_closure);
result
}));
let js_val = closure.as_ref().clone();
*rc1.borrow_mut() = Some(closure);
debug_assert_eq!(Rc::strong_count(&rc1), 2);
drop(rc1);
js_val
}
}
};
([$($unwind_safe:tt)*] $( ($($var:ident $arg1:ident $arg2:ident $arg3:ident $arg4:ident)*) )*) => ($(
closures!(@impl_for_args ($($var),*) FromWasmAbi [$($maybe_unwind_safe)*] $($var::from_abi($var) => $var $arg1 $arg2 $arg3 $arg4)*);
)*);
}
#[cfg(all(feature = "std", target_arch = "wasm32", panic = "unwind"))]
closures! {
[T: core::panic::UnwindSafe,]
()
(A a1 a2 a3 a4)
(A a1 a2 a3 a4 B b1 b2 b3 b4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4 G g1 g2 g3 g4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4 G g1 g2 g3 g4 H h1 h2 h3 h4)
}
#[cfg(not(all(feature = "std", target_arch = "wasm32", panic = "unwind")))]
closures! {
[]
()
(A a1 a2 a3 a4)
(A a1 a2 a3 a4 B b1 b2 b3 b4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4 G g1 g2 g3 g4)
(A a1 a2 a3 a4 B b1 b2 b3 b4 C c1 c2 c3 c4 D d1 d2 d3 d4 E e1 e2 e3 e4 F f1 f2 f3 f4 G g1 g2 g3 g4 H h1 h2 h3 h4)
}
// Comprehensive type-safe cross-function covariant and contravariant casting rules
macro_rules! impl_fn_upcasts {
() => {
impl_fn_upcasts!(@arities
[0 []]
[1 [A1 B1] O1]
[2 [A1 B1 A2 B2] O2]
[3 [A1 B1 A2 B2 A3 B3] O3]
[4 [A1 B1 A2 B2 A3 B3 A4 B4] O4]
[5 [A1 B1 A2 B2 A3 B3 A4 B4 A5 B5] O5]
[6 [A1 B1 A2 B2 A3 B3 A4 B4 A5 B5 A6 B6] O6]
[7 [A1 B1 A2 B2 A3 B3 A4 B4 A5 B5 A6 B6 A7 B7] O7]
[8 [A1 B1 A2 B2 A3 B3 A4 B4 A5 B5 A6 B6 A7 B7 A8 B8] O8]
);
};
(@arities) => {};
(@arities [$n:tt $args:tt $($opt:ident)?] $([$rest_n:tt $rest_args:tt $($rest_opt:ident)?])*) => {
impl_fn_upcasts!(@same $args);
impl_fn_upcasts!(@cross_all $args [] $([$rest_n $rest_args $($rest_opt)?])*);
impl_fn_upcasts!(@arities $([$rest_n $rest_args $($rest_opt)?])*);
};
(@same []) => {
impl<R1, R2> UpcastFrom<fn() -> R1> for fn() -> R2
where
R2: UpcastFrom<R1>
{}
impl<'a, R1, R2> UpcastFrom<dyn Fn() -> R1 + 'a> for dyn Fn() -> R2 + 'a
where
R2: UpcastFrom<R1>
{}
impl<'a, R1, R2> UpcastFrom<dyn FnMut() -> R1 + 'a> for dyn FnMut() -> R2 + 'a
where
R2: UpcastFrom<R1>
{}
};
// Arguments implemented with contravariance
(@same [$($A1:ident $A2:ident)+]) => {
impl<R1, R2, $($A1, $A2),+> UpcastFrom<fn($($A1),+) -> R1> for fn($($A2),+) -> R2
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+
{}
impl<'a, R1, R2, $($A1, $A2),+> UpcastFrom<dyn Fn($($A1),+) -> R1 + 'a> for dyn Fn($($A2),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+
{}
impl<'a, R1, R2, $($A1, $A2),+> UpcastFrom<dyn FnMut($($A1),+) -> R1 + 'a> for dyn FnMut($($A2),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+
{}
};
// Cross-all: done
(@cross_all $args:tt $opts:tt) => {};
// Cross-all: process next
(@cross_all $args:tt [$($opts:ident)*] [$next_n:tt $next_args:tt $next_opt:ident] $([$rest_n:tt $rest_args:tt $($rest_opt:ident)?])*) => {
impl_fn_upcasts!(@extend $args [$($opts)* $next_opt]);
impl_fn_upcasts!(@shrink $args [$($opts)* $next_opt]);
impl_fn_upcasts!(@cross_all $args [$($opts)* $next_opt] $([$rest_n $rest_args $($rest_opt)?])*);
};
// Extend: 0 -> N
(@extend [] [$($O:ident)+]) => {
impl<R1, R2, $($O),+> UpcastFrom<fn() -> R1> for fn($($O),+) -> R2
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($O),+> UpcastFrom<dyn Fn() -> R1 + 'a> for dyn Fn($($O),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($O),+> UpcastFrom<dyn FnMut() -> R1 + 'a> for dyn FnMut($($O),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
};
// Extend: N -> M
(@extend [$($A1:ident $A2:ident)+] [$($O:ident)+]) => {
impl<R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<fn($($A1),+) -> R1> for fn($($A2,)+ $($O),+) -> R2
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<dyn Fn($($A1),+) -> R1 + 'a> for dyn Fn($($A2,)+ $($O),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<dyn FnMut($($A1),+) -> R1 + 'a> for dyn FnMut($($A2,)+ $($O),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
};
// Shrink: N -> 0
(@shrink [] [$($O:ident)+]) => {
impl<R1, R2, $($O),+> UpcastFrom<fn($($O),+) -> R1> for fn() -> R2
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($O),+> UpcastFrom<dyn Fn($($O),+) -> R1 + 'a> for dyn Fn() -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($O),+> UpcastFrom<dyn FnMut($($O),+) -> R1 + 'a> for dyn FnMut() -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($O: UpcastFrom<Undefined>,)+
{}
};
// Shrink: M -> N
(@shrink [$($A1:ident $A2:ident)+] [$($O:ident)+]) => {
impl<R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<fn($($A1,)+ $($O),+) -> R1> for fn($($A2),+) -> R2
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<dyn Fn($($A1,)+ $($O),+) -> R1 + 'a> for dyn Fn($($A2),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
impl<'a, R1, R2, $($A1, $A2,)+ $($O),+> UpcastFrom<dyn FnMut($($A1,)+ $($O),+) -> R1 + 'a> for dyn FnMut($($A2),+) -> R2 + 'a
where
R2: UpcastFrom<R1>,
$($A1: UpcastFrom<$A2>,)+ // Contravariant
$($O: UpcastFrom<Undefined>,)+
{}
};
}
impl_fn_upcasts!();
// Copy the above impls down here for where there's only one argument and it's a
// reference. We could add more impls for more kinds of references, but it
// becomes a combinatorial explosion quickly. Let's see how far we can get with
// just this one! Maybe someone else can figure out voodoo so we don't have to
// duplicate.
// We need to allow coherence leak check just for these traits because we're providing separate implementation for `Fn(&A)` variants when `Fn(A)` one already exists.
#[allow(coherence_leak_check)]
const _: () = {
#[cfg(all(feature = "std", target_arch = "wasm32", panic = "unwind"))]
closures!(@impl_for_args (&A) RefFromWasmAbi [T: core::panic::UnwindSafe,] &*A::ref_from_abi(A) => A a1 a2 a3 a4);
#[cfg(not(all(feature = "std", target_arch = "wasm32", panic = "unwind")))]
closures!(@impl_for_args (&A) RefFromWasmAbi [] &*A::ref_from_abi(A) => A a1 a2 a3 a4);
};
// UpcastFrom impl for ScopedClosure.
// ScopedClosure<T1> upcasts to ScopedClosure<T2> when the underlying closure type T1 upcasts to T2.
// The dyn Fn/FnMut UpcastFrom impls above encode correct variance (covariant return, contravariant args).
//
// The 'a: 'b bound is critical for soundness: it ensures the target lifetime 'b does not
// exceed the source lifetime 'a. Without it, upcast_into could fabricate a
// ScopedClosure<'static, _> from a short-lived ScopedClosure, enabling use-after-free.
impl<'a: 'b, 'b, T1, T2> UpcastFrom<ScopedClosure<'a, T1>> for ScopedClosure<'b, T2>
where
T1: ?Sized + WasmClosure,
T2: ?Sized + WasmClosure + UpcastFrom<T1>,
{
}
+901
View File
@@ -0,0 +1,901 @@
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::char;
use core::mem::{self, ManuallyDrop};
use core::ptr::NonNull;
use crate::__rt::marker::ErasableGeneric;
use crate::__rt::{WasmSignedWordRepr, WasmWordRepr};
use crate::convert::traits::{WasmAbi, WasmPrimitive};
use crate::convert::{
FromWasmAbi, IntoWasmAbi, LongRefFromWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi,
RefFromWasmAbi, ReturnWasmAbi, TryFromJsValue, UpcastFrom,
};
use crate::sys::Promising;
use crate::sys::{JsNullable, JsOption, Undefined};
use crate::{Clamped, JsError, JsValue, UnwrapThrowExt};
// Primitive types can always be passed over the ABI.
impl<T: WasmPrimitive> WasmAbi for T {
type Prim1 = Self;
type Prim2 = ();
type Prim3 = ();
type Prim4 = ();
#[inline]
fn split(self) -> (Self, (), (), ()) {
(self, (), (), ())
}
#[inline]
fn join(prim: Self, _: (), _: (), _: ()) -> Self {
prim
}
}
impl WasmAbi for i128 {
type Prim1 = u64;
type Prim2 = u64;
type Prim3 = ();
type Prim4 = ();
#[inline]
fn split(self) -> (u64, u64, (), ()) {
let low = self as u64;
let high = (self >> 64) as u64;
(low, high, (), ())
}
#[inline]
fn join(low: u64, high: u64, _: (), _: ()) -> Self {
(((high as u128) << 64) | low as u128) as i128
}
}
impl WasmAbi for u128 {
type Prim1 = u64;
type Prim2 = u64;
type Prim3 = ();
type Prim4 = ();
#[inline]
fn split(self) -> (u64, u64, (), ()) {
let low = self as u64;
let high = (self >> 64) as u64;
(low, high, (), ())
}
#[inline]
fn join(low: u64, high: u64, _: (), _: ()) -> Self {
((high as u128) << 64) | low as u128
}
}
impl<T: WasmAbi<Prim4 = ()>> WasmAbi for Option<T> {
/// Whether this `Option` is a `Some` value.
type Prim1 = u32;
type Prim2 = T::Prim1;
type Prim3 = T::Prim2;
type Prim4 = T::Prim3;
#[inline]
fn split(self) -> (u32, T::Prim1, T::Prim2, T::Prim3) {
match self {
None => (
0,
Default::default(),
Default::default(),
Default::default(),
),
Some(value) => {
let (prim1, prim2, prim3, ()) = value.split();
(1, prim1, prim2, prim3)
}
}
}
#[inline]
fn join(is_some: u32, prim1: T::Prim1, prim2: T::Prim2, prim3: T::Prim3) -> Self {
if is_some == 0 {
None
} else {
Some(T::join(prim1, prim2, prim3, ()))
}
}
}
macro_rules! type_wasm_native {
($($t:tt as $c:tt)*) => ($(
impl IntoWasmAbi for $t {
type Abi = $c;
#[inline]
fn into_abi(self) -> $c { self as $c }
}
impl FromWasmAbi for $t {
type Abi = $c;
#[inline]
unsafe fn from_abi(js: $c) -> Self { js as $t }
}
impl IntoWasmAbi for Option<$t> {
type Abi = Option<$c>;
#[inline]
fn into_abi(self) -> Self::Abi {
self.map(|v| v as $c)
}
}
impl FromWasmAbi for Option<$t> {
type Abi = Option<$c>;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
js.map(|v: $c| v as $t)
}
}
impl UpcastFrom<$t> for JsValue {}
impl UpcastFrom<$t> for JsOption<JsValue> {}
impl UpcastFrom<$t> for JsNullable<JsValue> {}
impl UpcastFrom<$t> for $t {}
)*)
}
type_wasm_native!(
i64 as i64
u64 as u64
i128 as i128
u128 as u128
f64 as f64
);
impl UpcastFrom<u64> for u128 {}
impl UpcastFrom<u64> for JsOption<u128> {}
impl UpcastFrom<u64> for JsNullable<u128> {}
impl UpcastFrom<i64> for i128 {}
impl UpcastFrom<i64> for JsOption<i128> {}
impl UpcastFrom<i64> for JsNullable<i128> {}
/// Sentinel value used to encode `None` for optional pointer-sized and
/// 32-bit numeric values transferred over the JS `number` ABI.
///
/// `2^53 - 1` (`Number.MAX_SAFE_INTEGER`) is chosen because it is:
/// - exactly representable as an `f64` (so JS round-trips it losslessly),
/// - outside the range of any valid `i32`/`u32`/`f32` value (so it can't
/// collide with a real `Some(...)` payload from those types), and
/// - far above any plausible wasm64 pointer (which is bounded by the
/// memory-64 address space limit, well below `2^53`).
const F64_ABI_OPTION_SENTINEL: f64 = 9007199254740991_f64;
macro_rules! type_wasm_native_f64_option {
($($t:tt as $c:tt)*) => ($(
impl IntoWasmAbi for $t {
type Abi = $c;
#[inline]
fn into_abi(self) -> $c { self as $c }
}
impl FromWasmAbi for $t {
type Abi = $c;
#[inline]
unsafe fn from_abi(js: $c) -> Self { js as $t }
}
unsafe impl ErasableGeneric for $t {
type Repr = $t;
}
impl Promising for $t {
type Resolution = $t;
}
impl IntoWasmAbi for Option<$t> {
type Abi = f64;
#[inline]
fn into_abi(self) -> Self::Abi {
self.map(|v| v as $c as f64).unwrap_or(F64_ABI_OPTION_SENTINEL)
}
}
impl FromWasmAbi for Option<$t> {
type Abi = f64;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
if js == F64_ABI_OPTION_SENTINEL {
None
} else {
Some(js as $c as $t)
}
}
}
impl UpcastFrom<$t> for JsValue {}
impl UpcastFrom<$t> for JsOption<JsValue> {}
impl UpcastFrom<$t> for JsNullable<JsValue> {}
impl UpcastFrom<$t> for $t {}
)*)
}
type_wasm_native_f64_option!(
i32 as i32
u32 as u32
f32 as f32
isize as WasmSignedWordRepr
usize as WasmWordRepr
);
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<isize> for i32 {}
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<isize> for JsOption<i32> {}
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<isize> for JsNullable<i32> {}
impl UpcastFrom<isize> for i64 {}
impl UpcastFrom<isize> for JsOption<i64> {}
impl UpcastFrom<isize> for JsNullable<i64> {}
impl UpcastFrom<isize> for i128 {}
impl UpcastFrom<isize> for JsOption<i128> {}
impl UpcastFrom<isize> for JsNullable<i128> {}
impl UpcastFrom<i32> for isize {}
impl UpcastFrom<i32> for JsOption<isize> {}
impl UpcastFrom<i32> for JsNullable<isize> {}
impl UpcastFrom<i32> for i64 {}
impl UpcastFrom<i32> for JsOption<i64> {}
impl UpcastFrom<i32> for JsNullable<i64> {}
impl UpcastFrom<i32> for i128 {}
impl UpcastFrom<i32> for JsOption<i128> {}
impl UpcastFrom<i32> for JsNullable<i128> {}
impl UpcastFrom<u32> for usize {}
impl UpcastFrom<u32> for JsOption<usize> {}
impl UpcastFrom<u32> for JsNullable<usize> {}
impl UpcastFrom<u32> for u64 {}
impl UpcastFrom<u32> for JsOption<u64> {}
impl UpcastFrom<u32> for JsNullable<u64> {}
impl UpcastFrom<u32> for u128 {}
impl UpcastFrom<u32> for JsOption<u128> {}
impl UpcastFrom<u32> for JsNullable<u128> {}
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<usize> for u32 {}
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<usize> for JsOption<u32> {}
#[cfg(target_pointer_width = "32")]
impl UpcastFrom<usize> for JsNullable<u32> {}
impl UpcastFrom<usize> for u64 {}
impl UpcastFrom<usize> for JsOption<u64> {}
impl UpcastFrom<usize> for JsNullable<u64> {}
impl UpcastFrom<usize> for u128 {}
impl UpcastFrom<usize> for JsOption<u128> {}
impl UpcastFrom<usize> for JsNullable<u128> {}
impl UpcastFrom<f32> for f64 {}
impl UpcastFrom<f32> for JsOption<f64> {}
impl UpcastFrom<f32> for JsNullable<f64> {}
/// The sentinel value is 0xFF_FFFF for primitives with less than 32 bits.
///
/// This value is used, so all small primitive types (`bool`, `i8`, `u8`,
/// `i16`, `u16`, `char`) can use the same JS glue code. `char::MAX` is
/// 0x10_FFFF btw.
const U32_ABI_OPTION_SENTINEL: u32 = 0x00FF_FFFFu32;
macro_rules! type_abi_as_u32 {
($($t:tt)*) => ($(
impl IntoWasmAbi for $t {
type Abi = u32;
#[inline]
fn into_abi(self) -> u32 { self as u32 }
}
impl FromWasmAbi for $t {
type Abi = u32;
#[inline]
unsafe fn from_abi(js: u32) -> Self { js as $t }
}
impl OptionIntoWasmAbi for $t {
#[inline]
fn none() -> u32 { U32_ABI_OPTION_SENTINEL }
}
impl OptionFromWasmAbi for $t {
#[inline]
fn is_none(js: &u32) -> bool { *js == U32_ABI_OPTION_SENTINEL }
}
unsafe impl ErasableGeneric for $t {
type Repr = $t;
}
impl Promising for $t {
type Resolution = $t;
}
impl UpcastFrom<$t> for JsValue {}
impl UpcastFrom<$t> for JsOption<JsValue> {}
impl UpcastFrom<$t> for JsNullable<JsValue> {}
impl UpcastFrom<$t> for $t {}
)*)
}
type_abi_as_u32!(i8 u8 i16 u16);
impl UpcastFrom<i8> for i16 {}
impl UpcastFrom<i8> for JsOption<i16> {}
impl UpcastFrom<i8> for JsNullable<i16> {}
impl UpcastFrom<i8> for i32 {}
impl UpcastFrom<i8> for JsOption<i32> {}
impl UpcastFrom<i8> for JsNullable<i32> {}
impl UpcastFrom<i8> for i64 {}
impl UpcastFrom<i8> for JsOption<i64> {}
impl UpcastFrom<i8> for JsNullable<i64> {}
impl UpcastFrom<i8> for i128 {}
impl UpcastFrom<i8> for JsOption<i128> {}
impl UpcastFrom<i8> for JsNullable<i128> {}
impl UpcastFrom<u8> for u16 {}
impl UpcastFrom<u8> for JsOption<u16> {}
impl UpcastFrom<u8> for JsNullable<u16> {}
impl UpcastFrom<u8> for u32 {}
impl UpcastFrom<u8> for JsOption<u32> {}
impl UpcastFrom<u8> for JsNullable<u32> {}
impl UpcastFrom<u8> for u64 {}
impl UpcastFrom<u8> for JsOption<u64> {}
impl UpcastFrom<u8> for JsNullable<u64> {}
impl UpcastFrom<u8> for u128 {}
impl UpcastFrom<u8> for JsOption<u128> {}
impl UpcastFrom<u8> for JsNullable<u128> {}
impl UpcastFrom<i16> for i32 {}
impl UpcastFrom<i16> for JsOption<i32> {}
impl UpcastFrom<i16> for JsNullable<i32> {}
impl UpcastFrom<i16> for i64 {}
impl UpcastFrom<i16> for JsOption<i64> {}
impl UpcastFrom<i16> for JsNullable<i64> {}
impl UpcastFrom<i16> for i128 {}
impl UpcastFrom<i16> for JsOption<i128> {}
impl UpcastFrom<i16> for JsNullable<i128> {}
impl UpcastFrom<u16> for u32 {}
impl UpcastFrom<u16> for JsOption<u32> {}
impl UpcastFrom<u16> for JsNullable<u32> {}
impl UpcastFrom<u16> for u64 {}
impl UpcastFrom<u16> for JsOption<u64> {}
impl UpcastFrom<u16> for JsNullable<u64> {}
impl UpcastFrom<u16> for u128 {}
impl UpcastFrom<u16> for JsOption<u128> {}
impl UpcastFrom<u16> for JsNullable<u128> {}
impl IntoWasmAbi for bool {
type Abi = u32;
#[inline]
fn into_abi(self) -> u32 {
self as u32
}
}
impl FromWasmAbi for bool {
type Abi = u32;
#[inline]
unsafe fn from_abi(js: u32) -> bool {
js != 0
}
}
impl OptionIntoWasmAbi for bool {
#[inline]
fn none() -> u32 {
U32_ABI_OPTION_SENTINEL
}
}
impl OptionFromWasmAbi for bool {
#[inline]
fn is_none(js: &u32) -> bool {
*js == U32_ABI_OPTION_SENTINEL
}
}
unsafe impl ErasableGeneric for bool {
type Repr = bool;
}
impl Promising for bool {
type Resolution = bool;
}
impl UpcastFrom<bool> for JsValue {}
impl UpcastFrom<bool> for JsOption<JsValue> {}
impl UpcastFrom<bool> for JsNullable<JsValue> {}
impl UpcastFrom<bool> for bool {}
impl IntoWasmAbi for char {
type Abi = u32;
#[inline]
fn into_abi(self) -> u32 {
self as u32
}
}
impl FromWasmAbi for char {
type Abi = u32;
#[inline]
unsafe fn from_abi(js: u32) -> char {
// SAFETY: Checked in bindings.
char::from_u32_unchecked(js)
}
}
impl OptionIntoWasmAbi for char {
#[inline]
fn none() -> u32 {
U32_ABI_OPTION_SENTINEL
}
}
impl OptionFromWasmAbi for char {
#[inline]
fn is_none(js: &u32) -> bool {
*js == U32_ABI_OPTION_SENTINEL
}
}
unsafe impl ErasableGeneric for char {
type Repr = char;
}
impl Promising for char {
type Resolution = char;
}
impl UpcastFrom<char> for JsValue {}
impl UpcastFrom<char> for JsOption<JsValue> {}
impl UpcastFrom<char> for JsNullable<JsValue> {}
impl UpcastFrom<char> for char {}
impl<T> IntoWasmAbi for *const T {
type Abi = WasmWordRepr;
#[inline]
fn into_abi(self) -> Self::Abi {
self as usize as WasmWordRepr
}
}
impl<T> FromWasmAbi for *const T {
type Abi = WasmWordRepr;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> *const T {
js as usize as *const T
}
}
unsafe impl<T: ErasableGeneric> ErasableGeneric for *const T {
type Repr = *const T::Repr;
}
impl<T, Target> UpcastFrom<*const T> for *const Target where Target: UpcastFrom<T> {}
impl<T, Target> UpcastFrom<*const T> for JsOption<*const Target> where Target: UpcastFrom<T> {}
impl<T, Target> UpcastFrom<*const T> for JsNullable<*const Target> where Target: UpcastFrom<T> {}
impl<T> IntoWasmAbi for Option<*const T> {
type Abi = f64;
#[inline]
fn into_abi(self) -> Self::Abi {
self.map(|ptr| ptr as usize as f64)
.unwrap_or(F64_ABI_OPTION_SENTINEL)
}
}
unsafe impl<T: ErasableGeneric> ErasableGeneric for Option<T> {
type Repr = Option<<T as ErasableGeneric>::Repr>;
}
impl<T, Target> UpcastFrom<Option<T>> for Option<Target> where Target: UpcastFrom<T> {}
impl<T, Target> UpcastFrom<Option<T>> for JsOption<Option<Target>> where Target: UpcastFrom<T> {}
impl<T, Target> UpcastFrom<Option<T>> for JsNullable<Option<Target>> where Target: UpcastFrom<T> {}
impl<T> FromWasmAbi for Option<*const T> {
type Abi = f64;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Option<*const T> {
if js == F64_ABI_OPTION_SENTINEL {
None
} else {
Some(js as usize as *const T)
}
}
}
impl<T> IntoWasmAbi for *mut T {
type Abi = WasmWordRepr;
#[inline]
fn into_abi(self) -> Self::Abi {
self as usize as WasmWordRepr
}
}
impl<T> FromWasmAbi for *mut T {
type Abi = WasmWordRepr;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> *mut T {
js as usize as *mut T
}
}
impl<T> IntoWasmAbi for Option<*mut T> {
type Abi = f64;
#[inline]
fn into_abi(self) -> Self::Abi {
self.map(|ptr| ptr as usize as f64)
.unwrap_or(F64_ABI_OPTION_SENTINEL)
}
}
impl<T> FromWasmAbi for Option<*mut T> {
type Abi = f64;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Option<*mut T> {
if js == F64_ABI_OPTION_SENTINEL {
None
} else {
Some(js as usize as *mut T)
}
}
}
impl<T> IntoWasmAbi for NonNull<T> {
type Abi = WasmWordRepr;
#[inline]
fn into_abi(self) -> Self::Abi {
self.as_ptr() as usize as WasmWordRepr
}
}
impl<T> OptionIntoWasmAbi for NonNull<T> {
#[inline]
fn none() -> Self::Abi {
0 as WasmWordRepr
}
}
impl<T> FromWasmAbi for NonNull<T> {
type Abi = WasmWordRepr;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
// SAFETY: Checked in bindings.
NonNull::new_unchecked(js as usize as *mut T)
}
}
impl<T> OptionFromWasmAbi for NonNull<T> {
#[inline]
fn is_none(js: &Self::Abi) -> bool {
*js == 0 as WasmWordRepr
}
}
impl IntoWasmAbi for JsValue {
type Abi = u32;
#[inline]
fn into_abi(self) -> u32 {
let ret = self.idx;
mem::forget(self);
ret
}
}
impl FromWasmAbi for JsValue {
type Abi = u32;
#[inline]
unsafe fn from_abi(js: u32) -> JsValue {
JsValue::_new(js)
}
}
impl IntoWasmAbi for &JsValue {
type Abi = u32;
#[inline]
fn into_abi(self) -> u32 {
self.idx
}
}
impl RefFromWasmAbi for JsValue {
type Abi = u32;
type Anchor = ManuallyDrop<JsValue>;
#[inline]
unsafe fn ref_from_abi(js: u32) -> Self::Anchor {
ManuallyDrop::new(JsValue::_new(js))
}
}
impl LongRefFromWasmAbi for JsValue {
type Abi = u32;
type Anchor = JsValue;
#[inline]
unsafe fn long_ref_from_abi(js: u32) -> Self::Anchor {
Self::from_abi(js)
}
}
impl OptionIntoWasmAbi for JsValue {
#[inline]
fn none() -> u32 {
crate::__rt::JSIDX_UNDEFINED
}
}
impl OptionIntoWasmAbi for &JsValue {
#[inline]
fn none() -> u32 {
crate::__rt::JSIDX_UNDEFINED
}
}
impl OptionFromWasmAbi for JsValue {
#[inline]
fn is_none(js: &u32) -> bool {
unsafe { Self::ref_from_abi(*js) }.is_undefined()
}
}
impl<T: OptionIntoWasmAbi> IntoWasmAbi for Option<T> {
type Abi = T::Abi;
#[inline]
fn into_abi(self) -> T::Abi {
match self {
None => T::none(),
Some(me) => me.into_abi(),
}
}
}
impl<T: OptionFromWasmAbi> FromWasmAbi for Option<T> {
type Abi = T::Abi;
#[inline]
unsafe fn from_abi(js: T::Abi) -> Self {
if T::is_none(&js) {
None
} else {
Some(T::from_abi(js))
}
}
}
impl<T: OptionIntoWasmAbi + ErasableGeneric<Repr = JsValue> + Promising> Promising for Option<T> {
type Resolution = Option<<T as Promising>::Resolution>;
}
impl<T: IntoWasmAbi> IntoWasmAbi for Clamped<T> {
type Abi = T::Abi;
#[inline]
fn into_abi(self) -> Self::Abi {
self.0.into_abi()
}
}
impl<T: FromWasmAbi> FromWasmAbi for Clamped<T> {
type Abi = T::Abi;
#[inline]
unsafe fn from_abi(js: T::Abi) -> Self {
Clamped(T::from_abi(js))
}
}
impl IntoWasmAbi for () {
type Abi = ();
#[inline]
fn into_abi(self) {
self
}
}
impl FromWasmAbi for () {
type Abi = ();
#[inline]
unsafe fn from_abi(_js: ()) {}
}
impl Promising for () {
type Resolution = Undefined;
}
impl UpcastFrom<()> for JsValue {}
impl UpcastFrom<()> for () {}
unsafe impl ErasableGeneric for () {
type Repr = ();
}
impl<T: WasmAbi<Prim3 = (), Prim4 = ()>> WasmAbi for Result<T, u32> {
type Prim1 = T::Prim1;
type Prim2 = T::Prim2;
// The order of primitives here is such that we can pop() the possible error
// first, deal with it and move on. Later primitives are popped off the
// stack first.
/// If this `Result` is an `Err`, the error value.
type Prim3 = u32;
/// Whether this `Result` is an `Err`.
type Prim4 = u32;
#[inline]
fn split(self) -> (T::Prim1, T::Prim2, u32, u32) {
match self {
Ok(value) => {
let (prim1, prim2, (), ()) = value.split();
(prim1, prim2, 0, 0)
}
Err(err) => (Default::default(), Default::default(), err, 1),
}
}
#[inline]
fn join(prim1: T::Prim1, prim2: T::Prim2, err: u32, is_err: u32) -> Self {
if is_err == 0 {
Ok(T::join(prim1, prim2, (), ()))
} else {
Err(err)
}
}
}
impl<T, E> ReturnWasmAbi for Result<T, E>
where
T: IntoWasmAbi,
E: Into<JsValue>,
T::Abi: WasmAbi<Prim3 = (), Prim4 = ()>,
{
type Abi = Result<T::Abi, u32>;
#[inline]
fn return_abi(self) -> Self::Abi {
match self {
Ok(v) => Ok(v.into_abi()),
Err(e) => {
let jsval = e.into();
Err(jsval.into_abi())
}
}
}
}
unsafe impl<T: ErasableGeneric, E: ErasableGeneric> ErasableGeneric for Result<T, E> {
type Repr = Result<<T as ErasableGeneric>::Repr, <E as ErasableGeneric>::Repr>;
}
impl<T: ErasableGeneric + Promising, E: ErasableGeneric> Promising for Result<T, E> {
type Resolution = Result<<T as Promising>::Resolution, E>;
}
impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for Result<TargetT, TargetE>
where
TargetT: UpcastFrom<T>,
TargetE: UpcastFrom<E>,
{
}
impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for JsOption<Result<TargetT, TargetE>>
where
TargetT: UpcastFrom<T>,
TargetE: UpcastFrom<E>,
{
}
impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for JsNullable<Result<TargetT, TargetE>>
where
TargetT: UpcastFrom<T>,
TargetE: UpcastFrom<E>,
{
}
unsafe impl ErasableGeneric for JsError {
type Repr = JsValue;
}
impl IntoWasmAbi for JsError {
type Abi = <JsValue as IntoWasmAbi>::Abi;
fn into_abi(self) -> Self::Abi {
self.value.into_abi()
}
}
// `JsError` is `#[repr(transparent)]` over `JsValue`
impl FromWasmAbi for JsError {
type Abi = <JsValue as FromWasmAbi>::Abi;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
JsError {
value: JsValue::from_abi(js),
}
}
}
impl Promising for JsError {
type Resolution = JsError;
}
impl UpcastFrom<JsError> for JsValue {}
impl UpcastFrom<JsError> for JsOption<JsValue> {}
impl UpcastFrom<JsError> for JsNullable<JsValue> {}
impl UpcastFrom<JsError> for JsError {}
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
// Note: this can't take `&[T]` because the `Into<JsValue>` impl needs
// ownership of `T`.
pub fn js_value_vector_into_abi<T: Into<JsValue>>(
vector: Box<[T]>,
) -> <Box<[JsValue]> as IntoWasmAbi>::Abi {
let js_vals: Box<[JsValue]> = vector.into_vec().into_iter().map(|x| x.into()).collect();
js_vals.into_abi()
}
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub unsafe fn js_value_vector_from_abi<T: TryFromJsValue>(
js: <Box<[JsValue]> as FromWasmAbi>::Abi,
) -> Box<[T]> {
let js_vals = <Vec<JsValue> as FromWasmAbi>::from_abi(js);
let mut result = Vec::with_capacity(js_vals.len());
for value in js_vals {
// We push elements one-by-one instead of using `collect` in order to improve
// error messages. When using `collect`, this `expect_throw` is buried in a
// giant chain of internal iterator functions, which results in the actual
// function that takes this `Vec` falling off the end of the call stack.
// So instead, make sure to call it directly within this function.
//
// This is only a problem in debug mode. Since this is the browser's error stack
// we're talking about, it can only see functions that actually make it to the
// final Wasm binary (i.e., not inlined functions). All of those internal
// iterator functions get inlined in release mode, and so they don't show up.
result.push(
T::try_from_js_value(value).expect_throw("array contains a value of the wrong type"),
);
}
result.into_boxed_slice()
}
+15
View File
@@ -0,0 +1,15 @@
//! # ⚠️ Unstable
//!
//! This is an internal module, no stability guarantees are provided. Use at
//! your own risk.
#![allow(clippy::missing_safety_doc)]
mod closures;
mod impls;
mod slices;
mod traits;
pub use self::impls::*;
pub use self::slices::{VectorRefIntoWasmAbi, WasmSlice};
pub use self::traits::*;
+581
View File
@@ -0,0 +1,581 @@
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::mem::{self, MaybeUninit};
use core::ops::{Deref, DerefMut};
use core::str;
use crate::__rt::{marker::ErasableGeneric, WasmWord};
use crate::__wbindgen_copy_to_typed_array;
use crate::convert::{
js_value_vector_from_abi, js_value_vector_into_abi, FromWasmAbi, IntoWasmAbi,
LongRefFromWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi, RefFromWasmAbi, RefMutFromWasmAbi,
UpcastFrom, VectorFromWasmAbi, VectorIntoWasmAbi, WasmAbi,
};
use crate::describe::*;
use crate::JsValue;
use cfg_if::cfg_if;
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
// note: `WasmAbi` types do not need to be FFI-safe themselves, it's just more
// convenient to directly write `WasmSlice` in some of the manually-written FFI
// functions in `lib.rs` rather than `WasmRet<WasmSlice>`.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct WasmSlice {
pub ptr: WasmWord,
pub len: WasmWord,
}
impl WasmSlice {
#[inline]
pub fn from_usize(ptr: usize, len: usize) -> Self {
Self {
ptr: WasmWord::from_usize(ptr),
len: WasmWord::from_usize(len),
}
}
}
impl WasmAbi for WasmSlice {
/// `self.ptr`
type Prim1 = <WasmWord as WasmAbi>::Prim1;
/// `self.len`
type Prim2 = <WasmWord as WasmAbi>::Prim1;
type Prim3 = ();
type Prim4 = ();
#[inline]
fn split(self) -> (Self::Prim1, Self::Prim2, (), ()) {
(self.ptr.split().0, self.len.split().0, (), ())
}
#[inline]
fn join(ptr: Self::Prim1, len: Self::Prim2, _: (), _: ()) -> Self {
Self {
ptr: WasmWord::join(ptr, (), (), ()),
len: WasmWord::join(len, (), (), ()),
}
}
}
#[inline]
fn null_slice() -> WasmSlice {
WasmSlice::from_usize(0, 0)
}
pub struct WasmMutSlice {
pub slice: WasmSlice,
pub idx: u32,
}
impl WasmAbi for WasmMutSlice {
/// `self.slice.ptr`
type Prim1 = <WasmSlice as WasmAbi>::Prim1;
/// `self.slice.len`
type Prim2 = <WasmSlice as WasmAbi>::Prim2;
/// `self.idx`
type Prim3 = u32;
type Prim4 = ();
#[inline]
fn split(self) -> (Self::Prim1, Self::Prim2, u32, ()) {
let (ptr, len, (), ()) = self.slice.split();
(ptr, len, self.idx, ())
}
#[inline]
fn join(ptr: Self::Prim1, len: Self::Prim2, idx: u32, _: ()) -> Self {
Self {
slice: WasmSlice::join(ptr, len, (), ()),
idx,
}
}
}
/// The representation of a mutable slice passed from JS to Rust.
pub struct MutSlice<T> {
/// A copy of the data in the JS typed array.
contents: Box<[T]>,
/// A reference to the original JS typed array.
js: JsValue,
}
impl<T> Drop for MutSlice<T> {
fn drop(&mut self) {
let byte_slice = unsafe {
core::slice::from_raw_parts(
self.contents.as_ptr() as *const u8,
self.contents.len() * mem::size_of::<T>(),
)
};
__wbindgen_copy_to_typed_array(byte_slice, &self.js);
}
}
impl<T> Deref for MutSlice<T> {
type Target = [T];
fn deref(&self) -> &[T] {
&self.contents
}
}
impl<T> DerefMut for MutSlice<T> {
fn deref_mut(&mut self) -> &mut [T] {
&mut self.contents
}
}
macro_rules! vectors {
($($t:ty)*) => ($(
vectors_internal!($t);
vectors_internal!(MaybeUninit<$t>);
)*)
}
macro_rules! vectors_internal {
($t:ty) => {
impl WasmDescribeVector for $t {
#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
fn describe_vector() {
inform(VECTOR);
<$t>::describe();
}
}
impl VectorIntoWasmAbi for $t {
type Abi = WasmSlice;
#[inline]
fn vector_into_abi(vector: Box<[$t]>) -> WasmSlice {
let ptr = vector.as_ptr();
let len = vector.len();
mem::forget(vector);
WasmSlice::from_usize(ptr as usize, len)
}
}
impl VectorFromWasmAbi for $t {
type Abi = WasmSlice;
#[inline]
unsafe fn vector_from_abi(js: WasmSlice) -> Box<[$t]> {
let ptr = js.ptr.into_usize() as *mut $t;
let len = js.len.into_usize();
Vec::from_raw_parts(ptr, len, len).into_boxed_slice()
}
}
impl<'a> IntoWasmAbi for &'a [$t] {
type Abi = WasmSlice;
#[inline]
fn into_abi(self) -> WasmSlice {
WasmSlice::from_usize(self.as_ptr() as usize, self.len())
}
}
impl<'a> OptionIntoWasmAbi for &'a [$t] {
#[inline]
fn none() -> WasmSlice {
null_slice()
}
}
impl<'a> IntoWasmAbi for &'a mut [$t] {
type Abi = WasmSlice;
#[inline]
fn into_abi(self) -> WasmSlice {
(&*self).into_abi()
}
}
impl<'a> OptionIntoWasmAbi for &'a mut [$t] {
#[inline]
fn none() -> WasmSlice {
null_slice()
}
}
impl RefFromWasmAbi for [$t] {
type Abi = WasmSlice;
type Anchor = Box<[$t]>;
#[inline]
unsafe fn ref_from_abi(js: WasmSlice) -> Box<[$t]> {
<Box<[$t]>>::from_abi(js)
}
}
impl RefMutFromWasmAbi for [$t] {
type Abi = WasmMutSlice;
type Anchor = MutSlice<$t>;
#[inline]
unsafe fn ref_mut_from_abi(js: WasmMutSlice) -> MutSlice<$t> {
let contents = <Box<[$t]>>::from_abi(js.slice);
let js = JsValue::from_abi(js.idx);
MutSlice { contents, js }
}
}
impl LongRefFromWasmAbi for [$t] {
type Abi = WasmSlice;
type Anchor = Box<[$t]>;
#[inline]
unsafe fn long_ref_from_abi(js: WasmSlice) -> Box<[$t]> {
Self::ref_from_abi(js)
}
}
};
}
vectors! {
u8 i8 u16 i16 u32 i32 u64 i64 usize isize f32 f64
}
impl WasmDescribeVector for String {
#[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
fn describe_vector() {
inform(VECTOR);
inform(NAMED_EXTERNREF);
// Trying to use an actual loop for this breaks the Wasm interpreter.
inform(6);
inform('s' as u32);
inform('t' as u32);
inform('r' as u32);
inform('i' as u32);
inform('n' as u32);
inform('g' as u32);
}
}
impl VectorIntoWasmAbi for String {
type Abi = <Box<[JsValue]> as IntoWasmAbi>::Abi;
fn vector_into_abi(vector: Box<[Self]>) -> Self::Abi {
js_value_vector_into_abi(vector)
}
}
impl VectorFromWasmAbi for String {
type Abi = <Box<[JsValue]> as FromWasmAbi>::Abi;
unsafe fn vector_from_abi(js: Self::Abi) -> Box<[Self]> {
js_value_vector_from_abi(js)
}
}
cfg_if! {
if #[cfg(feature = "enable-interning")] {
#[inline]
fn unsafe_get_cached_str(x: &str) -> Option<WasmSlice> {
// This uses 0 for the ptr as an indication that it is a JsValue and not a str.
crate::cache::intern::unsafe_get_str(x).map(|x| WasmSlice::from_usize(0, x as usize))
}
} else {
#[inline]
fn unsafe_get_cached_str(_x: &str) -> Option<WasmSlice> {
None
}
}
}
impl<T> IntoWasmAbi for Vec<T>
where
Box<[T]>: IntoWasmAbi<Abi = WasmSlice>,
{
type Abi = <Box<[T]> as IntoWasmAbi>::Abi;
#[inline]
fn into_abi(self) -> Self::Abi {
self.into_boxed_slice().into_abi()
}
}
impl<T> OptionIntoWasmAbi for Vec<T>
where
Box<[T]>: IntoWasmAbi<Abi = WasmSlice>,
{
#[inline]
fn none() -> WasmSlice {
null_slice()
}
}
/// Internal trait used by the `slice_to_array` macro codegen.
///
/// Produces the wire representation JS observes when an outgoing `&[T]`
/// argument is rendered as a plain `Array`. There are two impl shapes,
/// neither of which requires `T: Clone`:
///
/// * For primitive numeric `T` (`u8`, `i32`, `f64`, ...) the wire is a
/// borrow of the slice memory directly — no allocation, no copy. The
/// JS-side shim performs `Array.from(typedArrayView)` to materialise
/// the JS `Array` and never frees the buffer.
/// * For everything else (`String`, `JsValue`, imported types, exported
/// types) the wire is a freshly allocated `Box<[u32]>` of externref
/// indices — one per element, constructed via `&T -> JsValue` (which
/// for handle-shaped types is a refcount bump on the existing JS
/// slot, and for `String` / value-shaped types creates a fresh JS
/// value). The JS-side shim reads the indices into a JS `Array` and
/// frees the index buffer.
///
/// Both shapes carry the same `WasmSlice` (ptr + len) on the wire. The
/// cli-support side picks the right JS shim based on the element
/// `VectorKind` recovered from the descriptor.
///
/// Not user-facing: users opt in via `#[wasm_bindgen(slice_to_array)]`
/// on an imported function or `extern "C"` block.
pub trait VectorRefIntoWasmAbi {
/// Construct the wire representation for `Some(slice)`. The returned
/// `WasmSlice` is either a borrow of the input slice (primitive
/// case) or a buffer JS owns and frees (handle-shaped case).
fn slice_into_abi(slice: &[Self]) -> WasmSlice
where
Self: Sized;
/// Wire representation for `None` (used by `Option<&[T]>`). A null
/// `WasmSlice` (`ptr == 0`) is the convention shared with every
/// other vector-like ABI in the crate.
#[inline]
fn slice_none() -> WasmSlice
where
Self: Sized,
{
null_slice()
}
}
macro_rules! vector_ref_into_wasm_abi_primitive {
($($t:ty)*) => ($(
impl VectorRefIntoWasmAbi for $t {
#[inline]
fn slice_into_abi(slice: &[Self]) -> WasmSlice {
// Borrow of the slice memory; the JS shim does
// `Array.from(view)` and never frees.
WasmSlice::from_usize(slice.as_ptr() as usize, slice.len())
}
}
)*);
}
vector_ref_into_wasm_abi_primitive!(u8 i8 u16 i16 u32 i32 u64 i64 usize isize f32 f64);
impl<T> VectorRefIntoWasmAbi for T
where
for<'a> &'a T: Into<JsValue>,
{
#[inline]
fn slice_into_abi(slice: &[Self]) -> WasmSlice {
// Build a fresh `[JsValue]` buffer one element at a time. The
// existing `Vec<JsValue>` ABI hands off the buffer to JS; the
// JS shim drops each externref slot it reads and frees the
// buffer.
let js_vals: Box<[JsValue]> = slice.iter().map(Into::into).collect();
js_vals.into_abi()
}
}
impl<T> FromWasmAbi for Vec<T>
where
Box<[T]>: FromWasmAbi<Abi = WasmSlice>,
{
type Abi = <Box<[T]> as FromWasmAbi>::Abi;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
<Box<[T]>>::from_abi(js).into()
}
}
impl<T> OptionFromWasmAbi for Vec<T>
where
Box<[T]>: FromWasmAbi<Abi = WasmSlice>,
{
#[inline]
fn is_none(abi: &WasmSlice) -> bool {
abi.ptr.is_zero()
}
}
impl IntoWasmAbi for String {
type Abi = <Vec<u8> as IntoWasmAbi>::Abi;
#[inline]
fn into_abi(self) -> Self::Abi {
// This is safe because the JsValue is immediately looked up in the heap and
// then returned, so use-after-free cannot occur.
unsafe_get_cached_str(&self).unwrap_or_else(|| self.into_bytes().into_abi())
}
}
impl OptionIntoWasmAbi for String {
#[inline]
fn none() -> Self::Abi {
null_slice()
}
}
impl FromWasmAbi for String {
type Abi = <Vec<u8> as FromWasmAbi>::Abi;
#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
String::from_utf8_unchecked(<Vec<u8>>::from_abi(js))
}
}
impl OptionFromWasmAbi for String {
#[inline]
fn is_none(slice: &WasmSlice) -> bool {
slice.ptr.is_zero()
}
}
impl<'a> IntoWasmAbi for &'a str {
type Abi = <&'a [u8] as IntoWasmAbi>::Abi;
#[inline]
fn into_abi(self) -> Self::Abi {
// This is safe because the JsValue is immediately looked up in the heap and
// then returned, so use-after-free cannot occur.
unsafe_get_cached_str(self).unwrap_or_else(|| self.as_bytes().into_abi())
}
}
impl OptionIntoWasmAbi for &str {
#[inline]
fn none() -> Self::Abi {
null_slice()
}
}
impl RefFromWasmAbi for str {
type Abi = <[u8] as RefFromWasmAbi>::Abi;
type Anchor = Box<str>;
#[inline]
unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor {
mem::transmute::<Box<[u8]>, Box<str>>(<Box<[u8]>>::from_abi(js))
}
}
impl LongRefFromWasmAbi for str {
type Abi = <[u8] as RefFromWasmAbi>::Abi;
type Anchor = Box<str>;
#[inline]
unsafe fn long_ref_from_abi(js: Self::Abi) -> Self::Anchor {
Self::ref_from_abi(js)
}
}
unsafe impl ErasableGeneric for &str {
type Repr = &'static str;
}
unsafe impl<T: ErasableGeneric> ErasableGeneric for Box<[T]> {
type Repr = Box<[T::Repr]>;
}
impl UpcastFrom<&str> for &str {}
impl<T, Target> UpcastFrom<Box<[T]>> for Box<[Target]> where Target: UpcastFrom<T> {}
unsafe impl<T: ErasableGeneric> ErasableGeneric for Vec<T> {
type Repr = Vec<T::Repr>;
}
impl<T, Target> UpcastFrom<Vec<T>> for Vec<Target> where Target: UpcastFrom<T> {}
impl<T: VectorIntoWasmAbi> IntoWasmAbi for Box<[T]> {
type Abi = <T as VectorIntoWasmAbi>::Abi;
fn into_abi(self) -> Self::Abi {
T::vector_into_abi(self)
}
}
impl<T> OptionIntoWasmAbi for Box<[T]>
where
Self: IntoWasmAbi<Abi = WasmSlice>,
{
fn none() -> WasmSlice {
null_slice()
}
}
impl<T: VectorFromWasmAbi> FromWasmAbi for Box<[T]> {
type Abi = <T as VectorFromWasmAbi>::Abi;
unsafe fn from_abi(js: Self::Abi) -> Self {
T::vector_from_abi(js)
}
}
impl<T> OptionFromWasmAbi for Box<[T]>
where
Self: FromWasmAbi<Abi = WasmSlice>,
{
fn is_none(slice: &WasmSlice) -> bool {
slice.ptr.is_zero()
}
}
impl<T: ErasableGeneric<Repr = JsValue> + WasmDescribe> VectorFromWasmAbi for T {
type Abi = WasmSlice;
#[inline]
unsafe fn vector_from_abi(js: WasmSlice) -> Box<[Self]> {
let ptr = js.ptr.into_usize() as *mut T;
let len = js.len.into_usize();
Vec::from_raw_parts(ptr, len, len).into_boxed_slice()
}
}
impl<T: ErasableGeneric<Repr = JsValue> + WasmDescribe> VectorIntoWasmAbi for T {
type Abi = WasmSlice;
#[inline]
fn vector_into_abi(vector: Box<[T]>) -> WasmSlice {
let ptr = vector.as_ptr();
let len = vector.len();
mem::forget(vector);
WasmSlice::from_usize(ptr as usize, len)
}
}
// JsValue-like slice support (Rust-to-JS only)
// JsValue-like are repr(transparent) over u32, so &[JsValue] is a contiguous array of heap indices
unsafe impl<T: ErasableGeneric> ErasableGeneric for &[T] {
type Repr = &'static [T::Repr];
}
impl<'a, T, Target> UpcastFrom<&'a [T]> for &'a [Target] where Target: UpcastFrom<T> {}
impl<T: ErasableGeneric<Repr = JsValue> + WasmDescribe> IntoWasmAbi for &[T] {
type Abi = WasmSlice;
#[inline]
fn into_abi(self) -> WasmSlice {
WasmSlice::from_usize(self.as_ptr() as usize, self.len())
}
}
impl<T: ErasableGeneric<Repr = JsValue> + WasmDescribe> OptionIntoWasmAbi for &[T] {
#[inline]
fn none() -> WasmSlice {
null_slice()
}
}
+671
View File
@@ -0,0 +1,671 @@
use core::borrow::Borrow;
use core::ops::{Deref, DerefMut};
use core::panic::AssertUnwindSafe;
use crate::sys::{JsNullable, JsOption};
use crate::{describe::*, JsCast};
use crate::{ErasableGeneric, JsValue};
/// A trait for anything that can be converted into a type that can cross the
/// Wasm ABI directly, eg `u32` or `f64`.
///
/// This is the opposite operation as `FromWasmAbi` and `Ref[Mut]FromWasmAbi`.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait IntoWasmAbi: WasmDescribe {
/// The Wasm ABI type that this converts into when crossing the ABI
/// boundary.
type Abi: WasmAbi;
/// Convert `self` into `Self::Abi` so that it can be sent across the wasm
/// ABI boundary.
fn into_abi(self) -> Self::Abi;
}
/// A trait for anything that can be recovered by-value from the Wasm ABI
/// boundary, eg a Rust `u8` can be recovered from the Wasm ABI `u32` type.
///
/// This is the by-value variant of the opposite operation as `IntoWasmAbi`.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait FromWasmAbi: WasmDescribe {
/// The Wasm ABI type that this converts from when coming back out from the
/// ABI boundary.
type Abi: WasmAbi;
/// Recover a `Self` from `Self::Abi`.
///
/// # Safety
///
/// This is only safe to call when -- and implementations may assume that --
/// the supplied `Self::Abi` was previously generated by a call to `<Self as
/// IntoWasmAbi>::into_abi()` or the moral equivalent in JS.
unsafe fn from_abi(js: Self::Abi) -> Self;
}
/// A trait for anything that can be recovered as some sort of shared reference
/// from the Wasm ABI boundary.
///
/// This is the shared reference variant of the opposite operation as
/// `IntoWasmAbi`.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait RefFromWasmAbi: WasmDescribe {
/// The Wasm ABI type references to `Self` are recovered from.
type Abi: WasmAbi;
/// The type that holds the reference to `Self` for the duration of the
/// invocation of the function that has an `&Self` parameter. This is
/// required to ensure that the lifetimes don't persist beyond one function
/// call, and so that they remain anonymous.
type Anchor: Deref<Target = Self>;
/// Recover a `Self::Anchor` from `Self::Abi`.
///
/// # Safety
///
/// Same as `FromWasmAbi::from_abi`.
unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor;
}
/// A version of the `RefFromWasmAbi` trait with the additional requirement
/// that the reference must remain valid as long as the anchor isn't dropped.
///
/// This isn't the case for `JsValue`'s `RefFromWasmAbi` implementation. To
/// avoid having to allocate a spot for the `JsValue` on the `JsValue` heap,
/// the `JsValue` is instead pushed onto the `JsValue` stack, and popped off
/// again after the function that the reference was passed to returns. So,
/// `JsValue` has a different `LongRefFromWasmAbi` implementation that behaves
/// the same as `FromWasmAbi`, putting the value on the heap.
///
/// This is needed for async functions, where the reference needs to be valid
/// for the whole length of the `Future`, rather than the initial synchronous
/// call.
///
/// 'long ref' is short for 'long-lived reference'.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait LongRefFromWasmAbi: WasmDescribe {
/// Same as `RefFromWasmAbi::Abi`
type Abi: WasmAbi;
/// Same as `RefFromWasmAbi::Anchor`
type Anchor: Borrow<Self>;
/// Same as `RefFromWasmAbi::ref_from_abi`
unsafe fn long_ref_from_abi(js: Self::Abi) -> Self::Anchor;
}
/// Dual of the `RefFromWasmAbi` trait, except for mutable references.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait RefMutFromWasmAbi: WasmDescribe {
/// Same as `RefFromWasmAbi::Abi`
type Abi: WasmAbi;
/// Same as `RefFromWasmAbi::Anchor`
type Anchor: DerefMut<Target = Self>;
/// Same as `RefFromWasmAbi::ref_from_abi`
unsafe fn ref_mut_from_abi(js: Self::Abi) -> Self::Anchor;
}
/// Indicates that this type can be passed to JS as `Option<Self>`.
///
/// This trait is used when implementing `IntoWasmAbi for Option<T>`.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait OptionIntoWasmAbi: IntoWasmAbi {
/// Returns an ABI instance indicating "none", which JS will interpret as
/// the `None` branch of this option.
///
/// It should be guaranteed that the `IntoWasmAbi` can never produce the ABI
/// value returned here.
fn none() -> Self::Abi;
}
/// Indicates that this type can be received from JS as `Option<Self>`.
///
/// This trait is used when implementing `FromWasmAbi for Option<T>`.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait OptionFromWasmAbi: FromWasmAbi {
/// Tests whether the argument is a "none" instance. If so it will be
/// deserialized as `None`, and otherwise it will be passed to
/// `FromWasmAbi`.
fn is_none(abi: &Self::Abi) -> bool;
}
/// A trait for any type which maps to a Wasm primitive type when used in FFI
/// (`i32`, `i64`, `f32`, or `f64`).
///
/// This is with the exception of `()` (and other zero-sized types), which are
/// also allowed because they're ignored: no arguments actually get added.
///
/// # Safety
///
/// This is an unsafe trait to implement as there's no guarantee the type
/// actually maps to a primitive type.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub unsafe trait WasmPrimitive: Default {}
unsafe impl WasmPrimitive for u32 {}
unsafe impl WasmPrimitive for i32 {}
unsafe impl WasmPrimitive for u64 {}
unsafe impl WasmPrimitive for i64 {}
unsafe impl WasmPrimitive for f32 {}
unsafe impl WasmPrimitive for f64 {}
unsafe impl WasmPrimitive for () {}
/// A trait which represents types that can be passed across the Wasm ABI
/// boundary, by being split into multiple Wasm primitive types.
///
/// Up to 4 primitives are supported; if you don't want to use all of them, you
/// can set the rest to `()`, which will cause them to be ignored.
///
/// You need to be careful how many primitives you use, however:
/// `Result<T, JsValue>` uses up 2 primitives to store the error, and so it
/// doesn't work if `T` uses more than 2 primitives.
///
/// So, if you're adding support for a type that needs 3 or more primitives and
/// is able to be returned, you have to add another primitive here.
///
/// There's already one type that uses 3 primitives: `&mut [T]`. However, it
/// can't be returned anyway, so it doesn't matter that
/// `Result<&mut [T], JsValue>` wouldn't work.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait WasmAbi {
type Prim1: WasmPrimitive;
type Prim2: WasmPrimitive;
type Prim3: WasmPrimitive;
type Prim4: WasmPrimitive;
/// Splits this type up into primitives to be sent over the ABI.
fn split(self) -> (Self::Prim1, Self::Prim2, Self::Prim3, Self::Prim4);
/// Reconstructs this type from primitives received over the ABI.
fn join(prim1: Self::Prim1, prim2: Self::Prim2, prim3: Self::Prim3, prim4: Self::Prim4)
-> Self;
}
/// A trait representing how to interpret the return value of a function for
/// the Wasm ABI.
///
/// This is very similar to the `IntoWasmAbi` trait and in fact has a blanket
/// implementation for all implementors of the `IntoWasmAbi`. The primary use
/// case of this trait is to enable functions to return `Result`, interpreting
/// an error as "rethrow this to JS"
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait ReturnWasmAbi: WasmDescribe {
/// Same as `IntoWasmAbi::Abi`
type Abi: WasmAbi;
/// Same as `IntoWasmAbi::into_abi`, except that it may throw and never
/// return in the case of `Err`.
fn return_abi(self) -> Self::Abi;
}
impl<T: IntoWasmAbi> ReturnWasmAbi for T {
type Abi = T::Abi;
#[inline]
fn return_abi(self) -> Self::Abi {
self.into_abi()
}
}
use alloc::boxed::Box;
use core::marker::Sized;
/// Trait for element types to implement IntoWasmAbi for vectors of
/// themselves.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait VectorIntoWasmAbi: WasmDescribeVector + Sized {
type Abi: WasmAbi;
fn vector_into_abi(vector: Box<[Self]>) -> Self::Abi;
}
/// Trait for element types to implement FromWasmAbi for vectors of
/// themselves.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait VectorFromWasmAbi: WasmDescribeVector + Sized {
type Abi: WasmAbi;
unsafe fn vector_from_abi(js: Self::Abi) -> Box<[Self]>;
}
/// A repr(C) struct containing all of the primitives of a `WasmAbi` type, in
/// order.
///
/// This is used as the return type of imported/exported functions. `WasmAbi`
/// types aren't guaranteed to be FFI-safe, so we can't return them directly:
/// instead we return this.
///
/// If all but one of the primitives is `()`, this corresponds to returning the
/// remaining primitive directly, otherwise a return pointer is used.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
#[repr(C)]
pub struct WasmRet<T: WasmAbi> {
prim1: T::Prim1,
prim2: T::Prim2,
prim3: T::Prim3,
prim4: T::Prim4,
}
impl<T: WasmAbi> From<T> for WasmRet<T> {
fn from(value: T) -> Self {
let (prim1, prim2, prim3, prim4) = value.split();
Self {
prim1,
prim2,
prim3,
prim4,
}
}
}
// Ideally this'd just be an `Into<T>` implementation, but unfortunately that
// doesn't work because of the orphan rule.
impl<T: WasmAbi> WasmRet<T> {
/// Joins the components of this `WasmRet` back into the type they represent.
pub fn join(self) -> T {
T::join(self.prim1, self.prim2, self.prim3, self.prim4)
}
}
/// [`TryFromJsValue`] is a trait for converting a JavaScript value ([`JsValue`])
/// into a Rust type. It is used by the [`wasm_bindgen`](wasm_bindgen_macro::wasm_bindgen)
/// proc-macro to allow conversion to user types.
///
/// The semantics of this trait for various types are designed to provide a runtime
/// analog of the static semantics implemented by the IntoWasmAbi function bindgen,
/// with the exception that conversions are constrained to not cast invalid types.
///
/// For example, where the Wasm static semantics will permit `foo(x: i32)` when passed
/// from JS `foo("5")` to treat that as `foo(5)`, this trait will instead throw. Apart
/// from these reduced type conversion cases, behaviours should otherwise match the
/// static semantics.
///
/// Types implementing this trait must specify their conversion logic from
/// [`JsValue`] to the Rust type, handling any potential errors that may occur
/// during the conversion process.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
pub trait TryFromJsValue: Sized {
/// Performs the conversion.
fn try_from_js_value(value: JsValue) -> Result<Self, JsValue> {
Self::try_from_js_value_ref(&value).ok_or(value)
}
/// Performs the conversion.
fn try_from_js_value_ref(value: &JsValue) -> Option<Self>;
}
impl<T: FromWasmAbi> FromWasmAbi for AssertUnwindSafe<T> {
type Abi = T::Abi;
unsafe fn from_abi(js: Self::Abi) -> Self {
AssertUnwindSafe(T::from_abi(js))
}
}
/// A trait for defining upcast relationships from a source type.
///
/// This is the inverse of [`Upcast<T>`] - instead of implementing
/// `impl Upcast<Target> for Source`, you implement `impl UpcastFrom<Source> for Target`.
///
/// # Why UpcastFrom?
///
/// This resolves Rust's orphan rule issues: you can implement `UpcastFrom<MyType>`
/// for external types when `MyType` is local to your crate, whereas implementing
/// `Upcast<ExternalType>` would be prohibited by orphan rules.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
///
/// # Relationship to Upcast
///
/// `UpcastFrom<S>` provides a blanket implementation of `Upcast<T>`:
/// ```ignore
/// impl<S, T> Upcast<T> for S where T: UpcastFrom<S> {}
/// ```
///
/// This means implementing `UpcastFrom<Source> for Target` automatically gives you
/// `Upcast<Target> for Source`, enabling `source.upcast()` to produce `Target`.
pub trait UpcastFrom<S: ?Sized> {}
/// A trait for type-safe generic upcasting.
///
/// # ⚠️ Unstable
///
/// This is part of the internal [`convert`](crate::convert) module, **no
/// stability guarantees** are provided. Use at your own risk. See its
/// documentation for more details.
///
/// # Note
///
/// `Upcast<T>` has a blanket implementation for all types where `T: UpcastFrom<Self>`.
/// New upcast relationships should typically be defined by implementing `FromUpcast`
/// rather than `Upcast` directly, to avoid orphan rule issues.
pub trait Upcast<T: ?Sized> {
/// Perform a zero-cost type-safe upcast to a wider ref type within the Wasm
/// bindgen generics type system.
///
/// This enables proper nested conversions that obey subtyping rules,
/// supporting strict API type checking.
///
/// The common pattern when passing a narrow type is to call `upcast()`
/// or `upcast_into()` to obtain the correct type for the function usage,
/// while ensuring safe type checked usage.
///
/// For example, if passing `Promise<Number>` as an argument to a function
/// where `Promise<JsValue>` is expected, or `Function<JsValue>` as an
/// argument where `Function<Number>` is expected.
///
/// This is a compile time conversion only by the nature of the erasable
/// generics type system.
#[inline]
fn upcast(&self) -> &T
where
Self: ErasableGeneric,
T: Sized + ErasableGeneric<Repr = <Self as ErasableGeneric>::Repr>,
{
unsafe { &*(self as *const Self as *const T) }
}
/// Perform a zero-cost type-safe upcast to a wider type within the Wasm
/// bindgen generics type system.
///
/// This enables proper nested conversions that obey subtyping rules,
/// supporting strict API type checking.
///
/// The common pattern when passing a narrow type is to call `upcast()`
/// or `upcast_into()` to obtain the correct type for the function usage,
/// while ensuring safe type checked usage.
///
/// For example, if passing `Promise<Number>` as an argument to a function
/// where `Promise<JsValue>` is expected, or `FunctionArgs<JsValue>` as an
/// argument where `FunctionArgs<Number>` is expected.
///
/// This is a compile time conversion only by the nature of the erasable
/// generics type system.
#[inline]
fn upcast_into(self) -> T
where
Self: Sized + ErasableGeneric,
T: Sized + ErasableGeneric<Repr = <Self as ErasableGeneric>::Repr>,
{
unsafe { core::mem::transmute_copy(&core::mem::ManuallyDrop::new(self)) }
}
}
// Blanket impl: UpcastFrom<S> for T implies Upcast<T> for S
impl<S, T> Upcast<T> for S
where
T: UpcastFrom<S> + ?Sized,
S: ?Sized,
{
}
// Reference impls using UpcastFrom.
//
// &mut T references are invariant. If you accept &mut T, you cannot upcast it
// and write back a different type the caller could see.
// Eg. this is not valid:
// ```ignore
// let mut string = JsString::from("valid");
// let string_ref: &mut JsString = &mut string;
// // If &mut T was modeled as just covariant, we could upcast this to
// // &mut JsValue.
// let js_value_ref: &mut JsValue = string_ref.upcast_into();
// *js_value_ref = Object::new().into();
// // string is still typed as JsString, but it now wraps a plain object.
// // Converting it to a Rust String throws because the value is not a string.
// let _ = String::from(&string);
// ```
//
// Requiring `UpcastFrom` in *both* directions means `T` and `Target` have to be
// mutually upcastable -- i.e. equivalent, with the same set of valid values.
// That is exactly what makes a `&mut` cast sound: anything written back through
// the wider `&mut Target` view is still a valid `T`. So this rejects every
// widening (the `JsString` -> `JsValue` case above, where `JsValue` does not
// upcast back to `JsString`), while still allowing casts between genuinely
// equivalent types in either direction. For example `()` and `Undefined` both
// model "nothing" and upcast to each other, so a
// `&mut Closure<dyn Fn(Undefined)>` can be upcast to a `&mut Closure<dyn Fn(())>`
// and back.
impl<'a, T: ?Sized, Target: ?Sized> UpcastFrom<&'a mut T> for &'a mut Target
where
Target: UpcastFrom<T>,
T: UpcastFrom<Target>,
{
}
// &T references are covariant, so we can allow from a specific type to a more general type
impl<'a, T, Target> UpcastFrom<&'a T> for &'a Target where Target: UpcastFrom<T> {}
// Tuple upcasts with structural covariance
macro_rules! impl_tuple_upcast {
([$($T:ident)+] [$($Target:ident)+]) => {
// Structural covariance: (T...) -> (Target...)
impl<$($T,)+ $($Target,)+> UpcastFrom<($($T,)+)> for ($($Target,)+)
where
$($Target: JsGeneric + UpcastFrom<$T>,)+
$($T: JsGeneric,)+
{
}
impl<$($T: JsGeneric,)+ $($Target: JsGeneric,)+> UpcastFrom<($($T,)+)> for JsOption<($($Target,)+)>
where
$($Target: JsGeneric + UpcastFrom<$T>,)+
$($T: JsGeneric,)+
{
}
impl<$($T: JsGeneric,)+ $($Target: JsGeneric,)+> UpcastFrom<($($T,)+)> for JsNullable<($($Target,)+)>
where
$($Target: JsGeneric + UpcastFrom<$T>,)+
$($T: JsGeneric,)+
{
}
};
}
impl_tuple_upcast!([T1][Target1]);
impl_tuple_upcast!([T1 T2] [Target1 Target2]);
impl_tuple_upcast!([T1 T2 T3] [Target1 Target2 Target3]);
impl_tuple_upcast!([T1 T2 T3 T4] [Target1 Target2 Target3 Target4]);
impl_tuple_upcast!([T1 T2 T3 T4 T5] [Target1 Target2 Target3 Target4 Target5]);
impl_tuple_upcast!([T1 T2 T3 T4 T5 T6] [Target1 Target2 Target3 Target4 Target5 Target6]);
impl_tuple_upcast!([T1 T2 T3 T4 T5 T6 T7] [Target1 Target2 Target3 Target4 Target5 Target6 Target7]);
impl_tuple_upcast!([T1 T2 T3 T4 T5 T6 T7 T8] [Target1 Target2 Target3 Target4 Target5 Target6 Target7 Target8]);
/// A convenience trait for types that erase to [`JsValue`].
///
/// This is a shorthand for `ErasableGeneric<Repr = JsValue>`, used as a bound
/// on generic parameters that must be representable as JavaScript values.
///
/// # When to Use
///
/// Use `JsGeneric` as a trait bound when you need a generic type that:
/// - Can be passed to/from JavaScript
/// - Is type-erased to `JsValue` at the FFI boundary
///
/// # Examples
///
/// ```ignore
/// use wasm_bindgen::JsGeneric;
///
/// fn process_js_values<T: JsGeneric>(items: &[T]) {
/// // T can be any JS-compatible type
/// }
/// ```
///
/// # Implementors
///
/// This trait is automatically implemented for all types that implement
/// `ErasableGeneric<Repr = JsValue>`, including:
/// - All `js_sys` types (`Object`, `Array`, `Function`, etc.)
/// - `JsValue` itself
/// - Custom types imported via `#[wasm_bindgen]`
pub trait JsGeneric:
ErasableGeneric<Repr = JsValue>
+ UpcastFrom<Self>
+ Upcast<Self>
+ Upcast<JsValue>
+ JsCast
+ 'static
{
}
impl<T: ErasableGeneric<Repr = JsValue> + UpcastFrom<T> + Upcast<JsValue> + JsCast + 'static>
JsGeneric for T
{
}
/// Value conversion from a type into its canonical [`JsGeneric`] form.
///
/// This trait allows types to be converted into JsGeneric supported types, which
/// are required to be erasably generic with JsValue.
///
/// The single associated type — rather than a free type parameter bounded by
/// `AsRef<T>` — is what makes collection-style APIs infer annotation-free.
/// Given an input `A`, there is exactly one `A::JsCanon`, so rustc never has
/// to search across multiple `AsRef` impls to pick a target element type.
///
/// # Implementations
///
/// Provided impls:
/// - [`JsValue`] in this crate.
/// - Every `#[wasm_bindgen]`-imported type (identity — emitted by the macro).
/// - Every generic `js_sys` container (`Array<T>`, `Promise<T>`, `Set<T>`, …)
/// provides its own identity impl owned by `js_sys`.
/// - References to cloneable implementors, so borrowed iteration can still
/// produce owned JS-generic values.
///
/// This trait is deliberately *not* blanket-implemented over all [`JsGeneric`]
/// types: each implementor explicitly opts in, which leaves room for future
/// wrapper types to pick a non-identity [`Self::JsCanon`].
///
/// # Example
///
/// ```ignore
/// use js_sys::{Array, Number};
///
/// let arr: Array<Number> = (0..10).map(Number::from).collect();
/// ```
pub trait IntoJsGeneric {
/// The canonical [`JsGeneric`] form of this type.
type JsCanon: JsGeneric;
/// Produce the canonical [`JsGeneric`] value for `self`.
fn to_js(self) -> Self::JsCanon;
}
impl IntoJsGeneric for JsValue {
type JsCanon = JsValue;
#[inline]
fn to_js(self) -> JsValue {
self
}
}
// Reference iteration clones the borrowed wrapper to produce an owned value,
// then delegates to that type's canonical conversion.
impl<T: IntoJsGeneric + Clone> IntoJsGeneric for &T {
type JsCanon = T::JsCanon;
#[inline]
fn to_js(self) -> T::JsCanon {
self.clone().to_js()
}
}
// Intentionally not a blanket `impl<T: JsGeneric> IntoJsGeneric for T`:
// that would lock in identity for every current and future `JsGeneric` type
// and prevent wrapper types from canonicalising to a different target.
// Instead, implementations are provided explicitly by each owning crate
// (macro-generated for user types; hand-written for `js_sys` containers).
/// Marker for types that cross the ABI as a JavaScript string.
///
/// Use as a bound on an `experimental_generic_mono` import's type parameter to
/// accept any Rust or JS string shape, each at its native wire format:
/// `String` and `&str` cross as UTF-8 buffers, `js_sys::JsString` and
/// `&js_sys::JsString` as handles — all arriving in JS as a string value.
///
/// This trait is sealed: it is implemented only for the string shapes above,
/// each of which is guaranteed to produce a JS string on the other side.
///
/// `OptionIntoWasmAbi` is a supertrait so that nullable string positions
/// (`Option<T>`) work under the same bound.
///
/// This trait is experimental, like `experimental_generic_mono` itself, and
/// may change or be removed as that feature stabilizes.
pub trait JsStringLike:
IntoWasmAbi + OptionIntoWasmAbi + crate::__rt::marker::JsStringLikeSealed
{
}
impl crate::__rt::marker::JsStringLikeSealed for alloc::string::String {}
impl crate::__rt::marker::JsStringLikeSealed for &str {}
impl JsStringLike for alloc::string::String {}
impl JsStringLike for &str {}