wasm-bindgen 0.2.130

Easy support for interacting between JS and Rust.
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
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 of `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 type whose shared references can cross the Wasm ABI, i.e.
/// `for<'a> &'a Self: IntoWasmAbi`.
///
/// Rust does not imply a trait's `where` clauses on `Self` the way it implies
/// supertraits, so an alias trait for that higher-ranked bound would not let
/// generic code use `&T: IntoWasmAbi`. This trait carries the conversion
/// itself instead, and `experimental_generic_mono` imports marshal a `&T`
/// argument through it, so `T: RefIntoWasmAbi` is the bound they declare. It
/// is sealed, holding exactly where the higher-ranked bound does.
///
/// # ⚠️ 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 RefIntoWasmAbi: ref_into_wasm_abi::Sealed {
    /// The Wasm ABI type that `&Self` converts into.
    type Abi: WasmAbi;

    /// Describe `&Self`.
    fn describe_ref();

    /// Convert `&self` into `Self::Abi`.
    fn ref_into_abi(&self) -> Self::Abi;
}

mod ref_into_wasm_abi {
    use super::IntoWasmAbi;

    pub trait Sealed {}

    impl<T: ?Sized> Sealed for T where for<'a> &'a T: IntoWasmAbi {}
}

impl<T: ?Sized, A: WasmAbi> RefIntoWasmAbi for T
where
    for<'a> &'a T: IntoWasmAbi<Abi = A>,
{
    type Abi = A;

    #[inline]
    fn describe_ref() {
        <&T as WasmDescribe>::describe()
    }

    #[inline]
    fn ref_into_abi(&self) -> A {
        IntoWasmAbi::into_abi(self)
    }
}

/// 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;

    /// Recover a `Self` from `Self::Abi`, or the message to throw when JS
    /// passed a value that `Self` rejects.
    ///
    /// A throw runs no destructors, so the generated wrappers convert every
    /// argument with this and throw only once all of them are released.
    /// Implementations must release anything `js` owns before returning an
    /// error.
    ///
    /// # Safety
    ///
    /// Same as `from_abi`.
    #[doc(hidden)]
    #[inline]
    unsafe fn try_from_abi(js: Self::Abi) -> Result<Self, &'static str>
    where
        Self: Sized,
    {
        Ok(Self::from_abi(js))
    }
}

/// 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;

    /// The fallible form of `ref_from_abi`, see `FromWasmAbi::try_from_abi`.
    ///
    /// # Safety
    ///
    /// Same as `FromWasmAbi::from_abi`.
    #[doc(hidden)]
    #[inline]
    unsafe fn try_ref_from_abi(js: Self::Abi) -> Result<Self::Anchor, &'static str> {
        Ok(Self::ref_from_abi(js))
    }
}

/// 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;

    /// The fallible form of `long_ref_from_abi`, see
    /// `FromWasmAbi::try_from_abi`.
    ///
    /// # Safety
    ///
    /// Same as `FromWasmAbi::from_abi`.
    #[doc(hidden)]
    #[inline]
    unsafe fn try_long_ref_from_abi(js: Self::Abi) -> Result<Self::Anchor, &'static str> {
        Ok(Self::long_ref_from_abi(js))
    }
}

/// 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;

    /// The fallible form of `ref_mut_from_abi`, see
    /// `FromWasmAbi::try_from_abi`.
    ///
    /// # Safety
    ///
    /// Same as `FromWasmAbi::from_abi`.
    #[doc(hidden)]
    #[inline]
    unsafe fn try_ref_mut_from_abi(js: Self::Abi) -> Result<Self::Anchor, &'static str> {
        Ok(Self::ref_mut_from_abi(js))
    }
}

/// Indicates that this type can be passed to JS as `Option<Self>` over its own
/// ABI, which has a spare value for `None`.
///
/// Implementing it provides [`MaybeIntoWasmAbi`], which `Option<T>` converts
/// through; a type whose ABI has no spare value implements that trait
/// directly instead.
///
/// # ⚠️ 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>` over
/// its own ABI. See [`OptionIntoWasmAbi`].
///
/// # ⚠️ 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;
}

/// The ABI of `Option<Self>`.
///
/// `Option<T>` takes its conversion from this trait, so every `T` implementing
/// it can be wrapped, including under a generic bound such as
/// `Option<impl JsNumberOrStringLike>`. A type whose own ABI has a spare value
/// for `None` implements [`OptionIntoWasmAbi`] instead and gets this trait
/// from the blanket impl; a type without one, such as `i32` or `f64`, picks a
/// wider `MaybeAbi` here.
///
/// # ⚠️ 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 MaybeIntoWasmAbi: IntoWasmAbi {
    /// The ABI of `Option<Self>`.
    type MaybeAbi: WasmAbi;

    /// Converts a value into the `Option<Self>` ABI.
    fn into_maybe_abi(self) -> Self::MaybeAbi;

    /// Returns the ABI value for `None`, which JS reads as `undefined`.
    ///
    /// It should be guaranteed that
    /// [`into_maybe_abi`](Self::into_maybe_abi) can never produce this value.
    fn none() -> Self::MaybeAbi;
}

/// The ABI of `Option<Self>` received from JS. See [`MaybeIntoWasmAbi`].
///
/// # ⚠️ 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 MaybeFromWasmAbi: FromWasmAbi {
    /// The ABI of `Option<Self>`.
    type MaybeAbi: WasmAbi;

    /// Recovers a value from the `Option<Self>` ABI, once
    /// [`is_none`](Self::is_none) has ruled `None` out.
    ///
    /// # Safety
    ///
    /// As for [`FromWasmAbi::from_abi`].
    unsafe fn from_maybe_abi(abi: Self::MaybeAbi) -> Self;

    #[doc(hidden)]
    #[inline]
    unsafe fn try_from_maybe_abi(abi: Self::MaybeAbi) -> Result<Self, &'static str>
    where
        Self: Sized,
    {
        Ok(Self::from_maybe_abi(abi))
    }

    /// Tests the ABI value for `None`.
    fn is_none(abi: &Self::MaybeAbi) -> bool;
}

/// The `Null` value of `Nullable<Self>`, which shares the ABI of
/// `Option<Self>` with a second spare value beside
/// [`none`](MaybeIntoWasmAbi::none).
///
/// `Nullable<T>` and `Option<Nullable<T>>` take their conversions from this
/// trait, so every `T` implementing it can be wrapped, including under a
/// generic bound such as `Nullable<impl JsStringLike>`.
///
/// # ⚠️ 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 NullableIntoWasmAbi: MaybeIntoWasmAbi {
    /// Returns the ABI value for `Nullable::Null`, which JS reads as `null`.
    ///
    /// It should be guaranteed that neither
    /// [`into_maybe_abi`](MaybeIntoWasmAbi::into_maybe_abi) nor
    /// [`none`](MaybeIntoWasmAbi::none) can produce this value.
    fn null() -> Self::MaybeAbi;
}

/// The `Null` test of `Nullable<Self>` received from JS. See
/// [`NullableIntoWasmAbi`].
///
/// # ⚠️ 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 NullableFromWasmAbi: MaybeFromWasmAbi {
    /// Tests the ABI value for `Nullable::Null`.
    fn is_null(abi: &Self::MaybeAbi) -> 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]>;

    /// The fallible form of `vector_from_abi`, see
    /// `FromWasmAbi::try_from_abi`.
    #[doc(hidden)]
    #[inline]
    unsafe fn try_vector_from_abi(js: Self::Abi) -> Result<Box<[Self]>, &'static str> {
        Ok(Self::vector_from_abi(js))
    }
}

/// 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 {
    /// Whether `Self` accepts `null` as a distinct value space, as
    /// `Nullable<T>` does. An enclosing `Option` then passes `null` through
    /// instead of reading it as `None`, so `Option<T>` is itself nullable
    /// exactly when `T` is not. `JsValue` does not set this: it accepts
    /// `null` as one value among all of them, not as a distinct space, and
    /// `Option<JsValue>` reads it as `None` like the ABI does. This is the
    /// JS-value side of [`NullableFromWasmAbi`], which claims `null` at the
    /// ABI.
    const NULLABLE: bool = false;

    /// 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))
    }

    #[inline]
    unsafe fn try_from_abi(js: Self::Abi) -> Result<Self, &'static str> {
        T::try_from_abi(js).map(AssertUnwindSafe)
    }
}

/// 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.
///
/// `&String`, `&Box<str>` and `&Cow<str>` are also accepted and cross like
/// `&str`. `&&str` is not; dereference it first.
///
/// 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`, `NullableIntoWasmAbi` and `VectorRefIntoWasmAbi` are
/// supertraits so that optional and nullable string positions (`Option<T>`,
/// `Nullable<T>`) and string slices (`&[T]`) work under the same bound. A slice arrives in JS as an `Array` of strings.
///
/// This trait is experimental, like `experimental_generic_mono` itself, and
/// may change or be removed as that feature stabilizes.
pub trait JsStringLike:
    IntoWasmAbi
    + OptionIntoWasmAbi
    + NullableIntoWasmAbi
    + crate::convert::VectorRefIntoWasmAbi
    + crate::__rt::marker::JsStringLikeSealed
{
}

macro_rules! impl_js_string_like {
    ($($t:ty),* $(,)?) => ($(
        impl crate::__rt::marker::JsStringLikeSealed for $t {}
        impl JsStringLike for $t {}
    )*)
}

impl_js_string_like!(
    alloc::string::String,
    &str,
    &alloc::string::String,
    &alloc::boxed::Box<str>,
    &alloc::borrow::Cow<'_, str>,
);