wry-bindgen 0.2.123-alpha.10

Native desktop implementation of wasm-bindgen APIs using wry
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::encode::{
    Anchored, BinaryDecode, BinaryEncode, BorrowScope, CallScoped, EncodeTypeDef, JsRef,
    ThrowingResult,
};
use crate::ipc::EncodedData;
use crate::{JsCast, JsValue};
use core::mem::ManuallyDrop;
use core::ops::Deref;

/// Marker for types accepted by wasm-bindgen-shaped APIs that conceptually
/// convert into a Wasm ABI value.
///
/// Wry-bindgen does not use wasm-bindgen's raw ABI transport on desktop; the
/// generated glue uses the binary protocol instead. These traits are kept as
/// markers for `js-sys`/`web-sys` signatures that use wasm-bindgen's unstable
/// conversion traits as bounds.
pub trait IntoWasmAbi: BinaryEncode + EncodeTypeDef {
    #[inline]
    fn into_abi(self) -> u32
    where
        Self: Sized + IntoAbiId,
    {
        self.into_abi_id()
    }
}

/// Marker for types accepted by wasm-bindgen-shaped APIs that conceptually
/// convert from a Wasm ABI value.
pub trait FromWasmAbi: BinaryDecode + EncodeTypeDef {
    /// Recreate a JS-reference-like value from a heap id.
    ///
    /// This is only a compatibility hook for crates that preserve `JsValue`
    /// references through serde or similar adapters. Generated Wry bindings use
    /// the binary protocol instead.
    ///
    /// # Safety
    ///
    /// The caller must pass an id for a live JavaScript heap value that is valid
    /// for `Self`.
    #[inline]
    unsafe fn from_abi(js: u32) -> Self
    where
        Self: Sized + FromAbiId,
    {
        unsafe { Self::from_abi_id(js) }
    }
}

/// Marker for types that may appear as `Option<T>` in wasm-bindgen-shaped APIs.
pub trait OptionIntoWasmAbi: IntoWasmAbi {}

/// Marker for types that may be received as `Option<T>` in wasm-bindgen-shaped APIs.
pub trait OptionFromWasmAbi: FromWasmAbi {}

/// Marker for values that have a wasm-bindgen ABI representation.
pub trait WasmAbi {}

/// Marker for types that can be borrowed from wasm-bindgen-shaped APIs.
pub trait RefFromWasmAbi {
    /// Recreate a non-dropping reference anchor from a heap id.
    ///
    /// # Safety
    ///
    /// The caller must pass an id for a live JavaScript heap value that remains
    /// valid for the returned anchor.
    #[inline]
    unsafe fn ref_from_abi(js: u32) -> AbiRef<Self>
    where
        Self: Sized + FromAbiId,
    {
        AbiRef(ManuallyDrop::new(unsafe { Self::from_abi_id(js) }))
    }
}

/// Non-dropping anchor returned by `RefFromWasmAbi::ref_from_abi`.
pub struct AbiRef<T>(ManuallyDrop<T>);

impl<T> Deref for AbiRef<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> AsRef<T> for AbiRef<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        self
    }
}

#[doc(hidden)]
pub trait IntoAbiId {
    fn into_abi_id(self) -> u32;
}

#[doc(hidden)]
pub trait FromAbiId {
    unsafe fn from_abi_id(js: u32) -> Self;
}

impl<T> IntoAbiId for T
where
    T: AsRef<JsValue>,
{
    #[inline]
    fn into_abi_id(self) -> u32 {
        let id = self.as_ref().js_ref().into_abi();
        core::mem::forget(self);
        id
    }
}

impl<T> FromAbiId for T
where
    T: JsCast,
{
    #[inline]
    unsafe fn from_abi_id(js: u32) -> Self {
        T::unchecked_from_js(JsValue::from_ref(JsRef::from_abi(js)))
    }
}

/// The wire type advertised to JS for a return value, in borrow scope `S` — the
/// return-side analog of [`ArgAbi<S>::Wire`](crate::convert::ArgAbi::Wire). For
/// [`CallScoped`] it is the value's own wire type; for [`Anchored`] it is the
/// `Promise` *resolution* (the export macro wraps it in the configured
/// `js_sys::Promise<…>`, since `Promise` lives in the external `js-sys` crate).
/// The encode/lower behavior lives on the [`ReturnSync`]/[`ReturnAsync`]
/// sub-traits, so a value implements only the scope(s) it is returnable in.
pub trait ReturnAbi<S: BorrowScope> {
    /// The type whose `TypeDef` is advertised to JS for this return value.
    type Wire: EncodeTypeDef;
}

/// Encode a synchronous export's return value as wire bytes. A blanket forwards
/// every `IntoWasmAbi` value directly; `Result` is carved out so its `Err` is
/// thrown in JS. Because `Result` is not `IntoWasmAbi` the two do not overlap,
/// and dispatch is by type (so it sees through type aliases).
pub trait ReturnSync: ReturnAbi<CallScoped> {
    /// Encode `self` as the function's return payload.
    fn return_abi(self, encoder: &mut EncodedData);
}

impl<T: IntoWasmAbi> ReturnAbi<CallScoped> for T {
    type Wire = T;
}
impl<T: IntoWasmAbi> ReturnSync for T {
    #[inline]
    fn return_abi(self, encoder: &mut EncodedData) {
        self.encode(encoder);
    }
}

impl<T, E> ReturnAbi<CallScoped> for Result<T, E>
where
    T: BinaryEncode + EncodeTypeDef,
    E: Into<JsValue>,
{
    type Wire = ThrowingResult<T, JsValue>;
}
impl<T, E> ReturnSync for Result<T, E>
where
    T: BinaryEncode + EncodeTypeDef,
    E: Into<JsValue>,
{
    #[inline]
    fn return_abi(self, encoder: &mut EncodedData) {
        ThrowingResult(self.map_err(Into::into)).encode(encoder);
    }
}

// An exported constructor hands JS the stored object's handle by value (JS then
// `__wrap`s it). `ObjectHandle` is not `IntoWasmAbi` and is only ever returned by
// a *sync* constructor, so it implements the sync scope only.
impl ReturnAbi<CallScoped> for crate::__rt::object_store::ObjectHandle {
    type Wire = Self;
}
impl ReturnSync for crate::__rt::object_store::ObjectHandle {
    #[inline]
    fn return_abi(self, encoder: &mut EncodedData) {
        self.encode(encoder);
    }
}

/// Converts a `JsValue` into a Rust type by checking at runtime.
pub trait TryFromJsValue: Sized {
    fn try_from_js_value(value: JsValue) -> Result<Self, JsValue> {
        Self::try_from_js_value_ref(&value).ok_or(value)
    }

    fn try_from_js_value_ref(value: &JsValue) -> Option<Self>;
}

/// Lowers the output of an exported `async fn` to the `Result<JsValue, JsValue>`
/// that backs a JS promise (an `Err` becomes a rejected promise). A blanket
/// covers every `Into<JsValue> + Promising` value; `Result` is carved out by type
/// (it does not overlap because `Result` is not `Into<JsValue>`). The promise
/// resolution type is [`ReturnAbi<Anchored>::Wire`], delegated to [`Promising`].
pub trait ReturnAsync: ReturnAbi<Anchored> {
    fn into_js_result(self) -> Result<JsValue, JsValue>;
}

impl<T> ReturnAbi<Anchored> for T
where
    T: Into<JsValue> + crate::sys::Promising,
    <T as crate::sys::Promising>::Resolution: EncodeTypeDef,
{
    type Wire = <T as crate::sys::Promising>::Resolution;
}
impl<T> ReturnAsync for T
where
    T: Into<JsValue> + crate::sys::Promising,
    <T as crate::sys::Promising>::Resolution: EncodeTypeDef,
{
    #[inline]
    fn into_js_result(self) -> Result<JsValue, JsValue> {
        Ok(self.into())
    }
}

impl<T, E> ReturnAbi<Anchored> for Result<T, E>
where
    T: Into<JsValue> + crate::sys::Promising,
    <T as crate::sys::Promising>::Resolution: EncodeTypeDef,
    E: Into<JsValue>,
{
    type Wire = <T as crate::sys::Promising>::Resolution;
}
impl<T, E> ReturnAsync for Result<T, E>
where
    T: Into<JsValue> + crate::sys::Promising,
    <T as crate::sys::Promising>::Resolution: EncodeTypeDef,
    E: Into<JsValue>,
{
    #[inline]
    fn into_js_result(self) -> Result<JsValue, JsValue> {
        match self {
            Ok(value) => Ok(value.into()),
            Err(error) => Err(error.into()),
        }
    }
}

/// Reconstructs the declared return type of an `async` import from the
/// `Result<JsValue, JsValue>` a settled JS promise yields. A `Result<T, E>`
/// return propagates a rejection as `Err`; any other return type panics on
/// rejection. `Result` is dispatched by type, so it is seen through aliases.
pub trait FromJsFuture: Sized {
    fn from_js_future(result: Result<JsValue, JsValue>) -> Self;
}

impl<T: TryFromJsValue> FromJsFuture for T {
    #[inline]
    fn from_js_future(result: Result<JsValue, JsValue>) -> Self {
        let value = result.expect("async function failed");
        T::try_from_js_value(value).expect("async function returned incompatible value")
    }
}

impl<T: TryFromJsValue, E: From<JsValue>> FromJsFuture for Result<T, E> {
    #[inline]
    fn from_js_future(result: Result<JsValue, JsValue>) -> Self {
        match result {
            Ok(value) => Ok(
                T::try_from_js_value(value).expect("async function returned incompatible value")
            ),
            Err(error) => Err(E::from(error)),
        }
    }
}

/// Marker for type-safe generic upcast relationships.
///
/// `Null` is a present JavaScript value, so it must not model absence by
/// upcasting into [`JsOption`](crate::sys::JsOption):
///
/// ```compile_fail
/// use wry_bindgen::convert::UpcastFrom;
/// use wry_bindgen::sys::{JsOption, Null};
/// use wry_bindgen::JsValue;
///
/// fn assert_upcast<S, T>()
/// where
///     T: UpcastFrom<S>,
/// {
/// }
///
/// assert_upcast::<Null, JsOption<JsValue>>();
/// ```
///
/// Mutable references are invariant, so widening `&mut T` to `&mut Target`
/// requires both directions to be valid:
///
/// ```compile_fail
/// use wry_bindgen::convert::UpcastFrom;
///
/// struct Specific;
/// struct General;
///
/// impl UpcastFrom<Specific> for General {}
///
/// fn assert_upcast<S, T: ?Sized>()
/// where
///     T: UpcastFrom<S>,
/// {
/// }
///
/// assert_upcast::<&mut Specific, &mut General>();
/// ```
pub trait UpcastFrom<S: ?Sized> {}

/// Type-safe generic upcast helper.
pub trait Upcast<T: ?Sized> {
    #[inline]
    fn upcast(&self) -> &T
    where
        Self: crate::__rt::marker::ErasableGeneric,
        T: Sized
            + crate::__rt::marker::ErasableGeneric<
                Repr = <Self as crate::__rt::marker::ErasableGeneric>::Repr,
            >,
    {
        unsafe { &*(self as *const Self as *const T) }
    }

    #[inline]
    fn upcast_into(self) -> T
    where
        Self: Sized + crate::__rt::marker::ErasableGeneric,
        T: Sized
            + crate::__rt::marker::ErasableGeneric<
                Repr = <Self as crate::__rt::marker::ErasableGeneric>::Repr,
            >,
    {
        unsafe { core::mem::transmute_copy(&core::mem::ManuallyDrop::new(self)) }
    }
}

impl<S, T> Upcast<T> for S
where
    T: UpcastFrom<S> + ?Sized,
    S: ?Sized,
{
}

impl<'a, T: ?Sized, Target: ?Sized> UpcastFrom<&'a mut T> for &'a mut Target
where
    Target: UpcastFrom<T>,
    T: UpcastFrom<Target>,
{
}
impl<'a, T, Target> UpcastFrom<&'a T> for &'a Target where Target: UpcastFrom<T> {}

macro_rules! impl_tuple_upcast {
    ([$($ty:ident)+] [$($target:ident)+]) => {
        impl<$($ty,)+ $($target,)+> UpcastFrom<($($ty,)+)> for ($($target,)+)
        where
            $($ty: JsGeneric,)+
            $($target: JsGeneric + UpcastFrom<$ty>,)+
        {
        }

        impl<$($ty,)+ $($target,)+> UpcastFrom<($($ty,)+)> for crate::sys::JsOption<($($target,)+)>
        where
            $($ty: JsGeneric,)+
            $($target: JsGeneric + UpcastFrom<$ty>,)+
        {
        }
    };
}

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]);

/// Convenience bound for JS values whose generic parameters erase to `JsValue`.
pub trait JsGeneric:
    crate::__rt::marker::ErasableGeneric<Repr = JsValue>
    + UpcastFrom<Self>
    + Upcast<Self>
    + Upcast<JsValue>
    + JsCast
    + crate::__rt::JsRefEncode
    + crate::__rt::EncodeTypeDef
    + crate::__rt::BinaryEncode
    + crate::__rt::BinaryDecode
    + crate::__rt::BatchableResult
    + 'static
{
}

impl<T> JsGeneric for T where
    T: crate::__rt::marker::ErasableGeneric<Repr = JsValue>
        + UpcastFrom<T>
        + Upcast<JsValue>
        + JsCast
        + crate::__rt::JsRefEncode
        + crate::__rt::EncodeTypeDef
        + crate::__rt::BinaryEncode
        + crate::__rt::BinaryDecode
        + crate::__rt::BatchableResult
        + 'static
{
}

/// Converts a value into its canonical JS-generic representation.
pub trait IntoJsGeneric {
    type JsCanon: JsGeneric;

    fn to_js(self) -> Self::JsCanon;
}

impl IntoJsGeneric for JsValue {
    type JsCanon = JsValue;

    #[inline]
    fn to_js(self) -> JsValue {
        self
    }
}

impl<T: IntoJsGeneric + Clone> IntoJsGeneric for &T {
    type JsCanon = T::JsCanon;

    #[inline]
    fn to_js(self) -> T::JsCanon {
        self.clone().to_js()
    }
}