wasmtime/runtime/
values.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
use crate::runtime::vm::TableElement;
use crate::store::{AutoAssertNoGc, StoreOpaque};
use crate::{
    prelude::*, AnyRef, ArrayRef, AsContext, AsContextMut, ExternRef, Func, HeapType, RefType,
    Rooted, RootedGcRefImpl, StructRef, ValType, V128,
};
use core::ptr;

pub use crate::runtime::vm::ValRaw;

/// Possible runtime values that a WebAssembly module can either consume or
/// produce.
///
/// Note that we inline the `enum Ref { ... }` variants into `enum Val { ... }`
/// here as a size optimization.
#[derive(Debug, Clone, Copy)]
pub enum Val {
    // NB: the ordering here is intended to match the ordering in
    // `ValType` to improve codegen when learning the type of a value.
    //
    /// A 32-bit integer.
    I32(i32),

    /// A 64-bit integer.
    I64(i64),

    /// A 32-bit float.
    ///
    /// Note that the raw bits of the float are stored here, and you can use
    /// `f32::from_bits` to create an `f32` value.
    F32(u32),

    /// A 64-bit float.
    ///
    /// Note that the raw bits of the float are stored here, and you can use
    /// `f64::from_bits` to create an `f64` value.
    F64(u64),

    /// A 128-bit number.
    V128(V128),

    /// A function reference.
    FuncRef(Option<Func>),

    /// An external reference.
    ExternRef(Option<Rooted<ExternRef>>),

    /// An internal reference.
    AnyRef(Option<Rooted<AnyRef>>),
}

macro_rules! accessors {
    ($bind:ident $(($variant:ident($ty:ty) $get:ident $unwrap:ident $cvt:expr))*) => ($(
        /// Attempt to access the underlying value of this `Val`, returning
        /// `None` if it is not the correct type.
        #[inline]
        pub fn $get(&self) -> Option<$ty> {
            if let Val::$variant($bind) = self {
                Some($cvt)
            } else {
                None
            }
        }

        /// Returns the underlying value of this `Val`, panicking if it's the
        /// wrong type.
        ///
        /// # Panics
        ///
        /// Panics if `self` is not of the right type.
        #[inline]
        pub fn $unwrap(&self) -> $ty {
            self.$get().expect(concat!("expected ", stringify!($ty)))
        }
    )*)
}

impl Val {
    /// Returns the null reference for the given heap type.
    #[inline]
    pub fn null_ref(heap_type: &HeapType) -> Val {
        Ref::null(&heap_type).into()
    }

    /// Returns the null function reference value.
    ///
    /// The return value has type `(ref null nofunc)` aka `nullfuncref` and is a
    /// subtype of all function references.
    #[inline]
    pub const fn null_func_ref() -> Val {
        Val::FuncRef(None)
    }

    /// Returns the null function reference value.
    ///
    /// The return value has type `(ref null extern)` aka `nullexternref` and is
    /// a subtype of all external references.
    #[inline]
    pub const fn null_extern_ref() -> Val {
        Val::ExternRef(None)
    }

    /// Returns the null function reference value.
    ///
    /// The return value has type `(ref null any)` aka `nullref` and is a
    /// subtype of all internal references.
    #[inline]
    pub const fn null_any_ref() -> Val {
        Val::AnyRef(None)
    }

    /// Returns the default value for the given type, if any exists.
    ///
    /// Returns `None` if there is no default value for the given type (for
    /// example, non-nullable reference types do not have a default value).
    pub fn default_for_ty(ty: &ValType) -> Option<Val> {
        match ty {
            ValType::I32 => Some(Val::I32(0)),
            ValType::I64 => Some(Val::I64(0)),
            ValType::F32 => Some(Val::F32(0)),
            ValType::F64 => Some(Val::F64(0)),
            ValType::V128 => Some(Val::V128(V128::from(0))),
            ValType::Ref(ref_ty) => {
                if ref_ty.is_nullable() {
                    Some(Val::null_ref(ref_ty.heap_type()))
                } else {
                    None
                }
            }
        }
    }

    /// Returns the corresponding [`ValType`] for this `Val`.
    ///
    /// # Errors
    ///
    /// Returns an error if this value is a GC reference that has since been
    /// unrooted.
    ///
    /// # Panics
    ///
    /// Panics if this value is associated with a different store.
    #[inline]
    pub fn ty(&self, store: impl AsContext) -> Result<ValType> {
        self.load_ty(&store.as_context().0)
    }

    #[inline]
    pub(crate) fn load_ty(&self, store: &StoreOpaque) -> Result<ValType> {
        Ok(match self {
            Val::I32(_) => ValType::I32,
            Val::I64(_) => ValType::I64,
            Val::F32(_) => ValType::F32,
            Val::F64(_) => ValType::F64,
            Val::V128(_) => ValType::V128,
            Val::ExternRef(Some(_)) => ValType::EXTERNREF,
            Val::ExternRef(None) => ValType::NULLFUNCREF,
            Val::FuncRef(None) => ValType::NULLFUNCREF,
            Val::FuncRef(Some(f)) => ValType::Ref(RefType::new(
                false,
                HeapType::ConcreteFunc(f.load_ty(store)),
            )),
            Val::AnyRef(None) => ValType::NULLREF,
            Val::AnyRef(Some(a)) => ValType::Ref(RefType::new(false, a._ty(store)?)),
        })
    }

    /// Does this value match the given type?
    ///
    /// Returns an error is an underlying `Rooted` has been unrooted.
    ///
    /// # Panics
    ///
    /// Panics if this value is not associated with the given store.
    pub fn matches_ty(&self, store: impl AsContext, ty: &ValType) -> Result<bool> {
        self._matches_ty(&store.as_context().0, ty)
    }

    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &ValType) -> Result<bool> {
        assert!(self.comes_from_same_store(store));
        assert!(ty.comes_from_same_engine(store.engine()));
        Ok(match (self, ty) {
            (Val::I32(_), ValType::I32)
            | (Val::I64(_), ValType::I64)
            | (Val::F32(_), ValType::F32)
            | (Val::F64(_), ValType::F64)
            | (Val::V128(_), ValType::V128) => true,

            (Val::FuncRef(f), ValType::Ref(ref_ty)) => Ref::from(*f)._matches_ty(store, ref_ty)?,
            (Val::ExternRef(e), ValType::Ref(ref_ty)) => {
                Ref::from(*e)._matches_ty(store, ref_ty)?
            }
            (Val::AnyRef(a), ValType::Ref(ref_ty)) => Ref::from(*a)._matches_ty(store, ref_ty)?,

            (Val::I32(_), _)
            | (Val::I64(_), _)
            | (Val::F32(_), _)
            | (Val::F64(_), _)
            | (Val::V128(_), _)
            | (Val::FuncRef(_), _)
            | (Val::ExternRef(_), _)
            | (Val::AnyRef(_), _) => false,
        })
    }

    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &ValType) -> Result<()> {
        if !self.comes_from_same_store(store) {
            bail!("value used with wrong store")
        }
        if !ty.comes_from_same_engine(store.engine()) {
            bail!("type used with wrong engine")
        }
        if self._matches_ty(store, ty)? {
            Ok(())
        } else {
            let actual_ty = self.load_ty(store)?;
            bail!("type mismatch: expected {ty}, found {actual_ty}")
        }
    }

    /// Convenience method to convert this [`Val`] into a [`ValRaw`].
    ///
    /// Returns an error if this value is a GC reference and the GC reference
    /// has been unrooted.
    ///
    /// # Unsafety
    ///
    /// This method is unsafe for the reasons that [`ExternRef::to_raw`] and
    /// [`Func::to_raw`] are unsafe.
    pub unsafe fn to_raw(&self, store: impl AsContextMut) -> Result<ValRaw> {
        match self {
            Val::I32(i) => Ok(ValRaw::i32(*i)),
            Val::I64(i) => Ok(ValRaw::i64(*i)),
            Val::F32(u) => Ok(ValRaw::f32(*u)),
            Val::F64(u) => Ok(ValRaw::f64(*u)),
            Val::V128(b) => Ok(ValRaw::v128(b.as_u128())),
            Val::ExternRef(e) => Ok(ValRaw::externref(match e {
                None => 0,
                Some(e) => e.to_raw(store)?,
            })),
            Val::AnyRef(e) => Ok(ValRaw::anyref(match e {
                None => 0,
                Some(e) => e.to_raw(store)?,
            })),
            Val::FuncRef(f) => Ok(ValRaw::funcref(match f {
                Some(f) => f.to_raw(store),
                None => ptr::null_mut(),
            })),
        }
    }

    /// Convenience method to convert a [`ValRaw`] into a [`Val`].
    ///
    /// # Unsafety
    ///
    /// This method is unsafe for the reasons that [`ExternRef::from_raw`] and
    /// [`Func::from_raw`] are unsafe. Additionally there's no guarantee
    /// otherwise that `raw` should have the type `ty` specified.
    pub unsafe fn from_raw(mut store: impl AsContextMut, raw: ValRaw, ty: ValType) -> Val {
        let mut store = AutoAssertNoGc::new(store.as_context_mut().0);
        Self::_from_raw(&mut store, raw, &ty)
    }

    pub(crate) unsafe fn _from_raw(
        store: &mut AutoAssertNoGc<'_>,
        raw: ValRaw,
        ty: &ValType,
    ) -> Val {
        match ty {
            ValType::I32 => Val::I32(raw.get_i32()),
            ValType::I64 => Val::I64(raw.get_i64()),
            ValType::F32 => Val::F32(raw.get_f32()),
            ValType::F64 => Val::F64(raw.get_f64()),
            ValType::V128 => Val::V128(raw.get_v128().into()),
            ValType::Ref(ref_ty) => {
                let ref_ = match ref_ty.heap_type() {
                    HeapType::Func | HeapType::ConcreteFunc(_) => {
                        Func::_from_raw(store, raw.get_funcref()).into()
                    }

                    HeapType::NoFunc => Ref::Func(None),

                    HeapType::Extern => ExternRef::_from_raw(store, raw.get_externref()).into(),

                    HeapType::NoExtern => Ref::Extern(None),

                    HeapType::Any
                    | HeapType::Eq
                    | HeapType::I31
                    | HeapType::Array
                    | HeapType::ConcreteArray(_)
                    | HeapType::Struct
                    | HeapType::ConcreteStruct(_) => {
                        AnyRef::_from_raw(store, raw.get_anyref()).into()
                    }

                    HeapType::None => Ref::Any(None),
                };
                assert!(
                    ref_ty.is_nullable() || !ref_.is_null(),
                    "if the type is not nullable, we shouldn't get null; got \
                     type = {ref_ty}, ref = {ref_:?}"
                );
                ref_.into()
            }
        }
    }

    accessors! {
        e
        (I32(i32) i32 unwrap_i32 *e)
        (I64(i64) i64 unwrap_i64 *e)
        (F32(f32) f32 unwrap_f32 f32::from_bits(*e))
        (F64(f64) f64 unwrap_f64 f64::from_bits(*e))
        (FuncRef(Option<&Func>) func_ref unwrap_func_ref e.as_ref())
        (ExternRef(Option<&Rooted<ExternRef>>) extern_ref unwrap_extern_ref e.as_ref())
        (AnyRef(Option<&Rooted<AnyRef>>) any_ref unwrap_any_ref e.as_ref())
        (V128(V128) v128 unwrap_v128 *e)
    }

    /// Get this value's underlying reference, if any.
    #[inline]
    pub fn ref_(self) -> Option<Ref> {
        match self {
            Val::FuncRef(f) => Some(Ref::Func(f)),
            Val::ExternRef(e) => Some(Ref::Extern(e)),
            Val::AnyRef(a) => Some(Ref::Any(a)),
            Val::I32(_) | Val::I64(_) | Val::F32(_) | Val::F64(_) | Val::V128(_) => None,
        }
    }

    /// Attempt to access the underlying `externref` value of this `Val`.
    ///
    /// If this is not an `externref`, then `None` is returned.
    ///
    /// If this is a null `externref`, then `Some(None)` is returned.
    ///
    /// If this is a non-null `externref`, then `Some(Some(..))` is returned.
    #[inline]
    pub fn externref(&self) -> Option<Option<&Rooted<ExternRef>>> {
        match self {
            Val::ExternRef(None) => Some(None),
            Val::ExternRef(Some(e)) => Some(Some(e)),
            _ => None,
        }
    }

    /// Returns the underlying `externref` value of this `Val`, panicking if it's the
    /// wrong type.
    ///
    /// If this is a null `externref`, then `None` is returned.
    ///
    /// If this is a non-null `externref`, then `Some(..)` is returned.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not a (nullable) `externref`.
    #[inline]
    pub fn unwrap_externref(&self) -> Option<&Rooted<ExternRef>> {
        self.externref().expect("expected externref")
    }

    /// Attempt to access the underlying `anyref` value of this `Val`.
    ///
    /// If this is not an `anyref`, then `None` is returned.
    ///
    /// If this is a null `anyref`, then `Some(None)` is returned.
    ///
    /// If this is a non-null `anyref`, then `Some(Some(..))` is returned.
    #[inline]
    pub fn anyref(&self) -> Option<Option<&Rooted<AnyRef>>> {
        match self {
            Val::AnyRef(None) => Some(None),
            Val::AnyRef(Some(e)) => Some(Some(e)),
            _ => None,
        }
    }

    /// Returns the underlying `anyref` value of this `Val`, panicking if it's the
    /// wrong type.
    ///
    /// If this is a null `anyref`, then `None` is returned.
    ///
    /// If this is a non-null `anyref`, then `Some(..)` is returned.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not a (nullable) `anyref`.
    #[inline]
    pub fn unwrap_anyref(&self) -> Option<&Rooted<AnyRef>> {
        self.anyref().expect("expected anyref")
    }

    /// Attempt to access the underlying `funcref` value of this `Val`.
    ///
    /// If this is not an `funcref`, then `None` is returned.
    ///
    /// If this is a null `funcref`, then `Some(None)` is returned.
    ///
    /// If this is a non-null `funcref`, then `Some(Some(..))` is returned.
    #[inline]
    pub fn funcref(&self) -> Option<Option<&Func>> {
        match self {
            Val::FuncRef(None) => Some(None),
            Val::FuncRef(Some(f)) => Some(Some(f)),
            _ => None,
        }
    }

    /// Returns the underlying `funcref` value of this `Val`, panicking if it's the
    /// wrong type.
    ///
    /// If this is a null `funcref`, then `None` is returned.
    ///
    /// If this is a non-null `funcref`, then `Some(..)` is returned.
    ///
    /// # Panics
    ///
    /// Panics if `self` is not a (nullable) `funcref`.
    #[inline]
    pub fn unwrap_funcref(&self) -> Option<&Func> {
        self.funcref().expect("expected funcref")
    }

    #[inline]
    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
        match self {
            Val::FuncRef(Some(f)) => f.comes_from_same_store(store),
            Val::FuncRef(None) => true,

            Val::ExternRef(Some(x)) => x.comes_from_same_store(store),
            Val::ExternRef(None) => true,

            Val::AnyRef(Some(a)) => a.comes_from_same_store(store),
            Val::AnyRef(None) => true,

            // Integers, floats, and vectors have no association with any
            // particular store, so they're always considered as "yes I came
            // from that store",
            Val::I32(_) | Val::I64(_) | Val::F32(_) | Val::F64(_) | Val::V128(_) => true,
        }
    }
}

impl From<i32> for Val {
    #[inline]
    fn from(val: i32) -> Val {
        Val::I32(val)
    }
}

impl From<i64> for Val {
    #[inline]
    fn from(val: i64) -> Val {
        Val::I64(val)
    }
}

impl From<f32> for Val {
    #[inline]
    fn from(val: f32) -> Val {
        Val::F32(val.to_bits())
    }
}

impl From<f64> for Val {
    #[inline]
    fn from(val: f64) -> Val {
        Val::F64(val.to_bits())
    }
}

impl From<Ref> for Val {
    #[inline]
    fn from(val: Ref) -> Val {
        match val {
            Ref::Extern(e) => Val::ExternRef(e),
            Ref::Func(f) => Val::FuncRef(f),
            Ref::Any(a) => Val::AnyRef(a),
        }
    }
}

impl From<Rooted<ExternRef>> for Val {
    #[inline]
    fn from(val: Rooted<ExternRef>) -> Val {
        Val::ExternRef(Some(val))
    }
}

impl From<Option<Rooted<ExternRef>>> for Val {
    #[inline]
    fn from(val: Option<Rooted<ExternRef>>) -> Val {
        Val::ExternRef(val)
    }
}

impl From<Rooted<AnyRef>> for Val {
    #[inline]
    fn from(val: Rooted<AnyRef>) -> Val {
        Val::AnyRef(Some(val))
    }
}

impl From<Option<Rooted<AnyRef>>> for Val {
    #[inline]
    fn from(val: Option<Rooted<AnyRef>>) -> Val {
        Val::AnyRef(val)
    }
}

impl From<Rooted<StructRef>> for Val {
    #[inline]
    fn from(val: Rooted<StructRef>) -> Val {
        Val::AnyRef(Some(val.into()))
    }
}

impl From<Option<Rooted<StructRef>>> for Val {
    #[inline]
    fn from(val: Option<Rooted<StructRef>>) -> Val {
        Val::AnyRef(val.map(Into::into))
    }
}

impl From<Rooted<ArrayRef>> for Val {
    #[inline]
    fn from(val: Rooted<ArrayRef>) -> Val {
        Val::AnyRef(Some(val.into()))
    }
}

impl From<Option<Rooted<ArrayRef>>> for Val {
    #[inline]
    fn from(val: Option<Rooted<ArrayRef>>) -> Val {
        Val::AnyRef(val.map(Into::into))
    }
}

impl From<Func> for Val {
    #[inline]
    fn from(val: Func) -> Val {
        Val::FuncRef(Some(val))
    }
}

impl From<Option<Func>> for Val {
    #[inline]
    fn from(val: Option<Func>) -> Val {
        Val::FuncRef(val)
    }
}

impl From<u128> for Val {
    #[inline]
    fn from(val: u128) -> Val {
        Val::V128(val.into())
    }
}

impl From<V128> for Val {
    #[inline]
    fn from(val: V128) -> Val {
        Val::V128(val)
    }
}

/// A reference.
///
/// References come in three broad flavors:
///
/// 1. Function references. These are references to a function that can be
///    invoked.
///
/// 2. External references. These are references to data that is external
///    and opaque to the Wasm guest, provided by the host.
///
/// 3. Internal references. These are references to allocations inside the
///    Wasm's heap, such as structs and arrays. These are part of the GC
///    proposal, and not yet implemented in Wasmtime.
///
/// At the Wasm level, there are nullable and non-nullable variants of each type
/// of reference. Both variants are represented with `Ref` at the Wasmtime API
/// level. For example, values of both `(ref extern)` and `(ref null extern)`
/// types will be represented as `Ref::Extern(Option<ExternRef>)` in the
/// Wasmtime API. Nullable references are represented as `Option<Ref>` where
/// null references are represented as `None`. Wasm can construct null
/// references via the `ref.null <heap-type>` instruction.
///
/// References are non-forgable: Wasm cannot create invalid references, for
/// example, by claiming that the integer `0xbad1bad2` is actually a reference.
#[derive(Debug, Clone)]
pub enum Ref {
    // NB: We have a variant for each of the type hierarchies defined in Wasm,
    // and push the `Option` that provides nullability into each variant. This
    // allows us to get the most-precise type of any reference value, whether it
    // is null or not, without any additional metadata.
    //
    // Consider if we instead had the nullability inside `Val::Ref` and each of
    // the `Ref` variants did not have an `Option`:
    //
    //     enum Val {
    //         Ref(Option<Ref>),
    //         // Etc...
    //     }
    //     enum Ref {
    //         Func(Func),
    //         External(ExternRef),
    //         // Etc...
    //     }
    //
    // In this scenario, what type would we return from `Val::ty` for
    // `Val::Ref(None)`? Because Wasm has multiple separate type hierarchies,
    // there is no single common bottom type for all the different kinds of
    // references. So in this scenario, `Val::Ref(None)` doesn't have enough
    // information to reconstruct the value's type. That's a problem for us
    // because we need to get a value's type at various times all over the code
    // base.
    //
    /// A first-class reference to a WebAssembly function.
    ///
    /// The host, or the Wasm guest, can invoke this function.
    ///
    /// The host can create function references via [`Func::new`] or
    /// [`Func::wrap`].
    ///
    /// The Wasm guest can create non-null function references via the
    /// `ref.func` instruction, or null references via the `ref.null func`
    /// instruction.
    Func(Option<Func>),

    /// A reference to an value outside of the Wasm heap.
    ///
    /// These references are opaque to the Wasm itself. Wasm can't create
    /// non-null external references, nor do anything with them accept pass them
    /// around as function arguments and returns and place them into globals and
    /// tables.
    ///
    /// Wasm can create null external references via the `ref.null extern`
    /// instruction.
    Extern(Option<Rooted<ExternRef>>),

    /// An internal reference.
    ///
    /// The `AnyRef` type represents WebAssembly `anyref` values. These can be
    /// references to `struct`s and `array`s or inline/unboxed 31-bit
    /// integers.
    ///
    /// Unlike `externref`, Wasm guests can directly allocate `anyref`s, and
    /// does not need to rely on the host to do that.
    Any(Option<Rooted<AnyRef>>),
}

impl From<Func> for Ref {
    #[inline]
    fn from(f: Func) -> Ref {
        Ref::Func(Some(f))
    }
}

impl From<Option<Func>> for Ref {
    #[inline]
    fn from(f: Option<Func>) -> Ref {
        Ref::Func(f)
    }
}

impl From<Rooted<ExternRef>> for Ref {
    #[inline]
    fn from(e: Rooted<ExternRef>) -> Ref {
        Ref::Extern(Some(e))
    }
}

impl From<Option<Rooted<ExternRef>>> for Ref {
    #[inline]
    fn from(e: Option<Rooted<ExternRef>>) -> Ref {
        Ref::Extern(e)
    }
}

impl From<Rooted<AnyRef>> for Ref {
    #[inline]
    fn from(e: Rooted<AnyRef>) -> Ref {
        Ref::Any(Some(e))
    }
}

impl From<Option<Rooted<AnyRef>>> for Ref {
    #[inline]
    fn from(e: Option<Rooted<AnyRef>>) -> Ref {
        Ref::Any(e)
    }
}

impl From<Rooted<StructRef>> for Ref {
    #[inline]
    fn from(e: Rooted<StructRef>) -> Ref {
        Ref::Any(Some(e.into()))
    }
}

impl From<Option<Rooted<StructRef>>> for Ref {
    #[inline]
    fn from(e: Option<Rooted<StructRef>>) -> Ref {
        Ref::Any(e.map(Into::into))
    }
}

impl From<Rooted<ArrayRef>> for Ref {
    #[inline]
    fn from(e: Rooted<ArrayRef>) -> Ref {
        Ref::Any(Some(e.into()))
    }
}

impl From<Option<Rooted<ArrayRef>>> for Ref {
    #[inline]
    fn from(e: Option<Rooted<ArrayRef>>) -> Ref {
        Ref::Any(e.map(Into::into))
    }
}

impl Ref {
    /// Create a null reference to the given heap type.
    #[inline]
    pub fn null(heap_type: &HeapType) -> Self {
        match heap_type.top() {
            HeapType::Any => Ref::Any(None),
            HeapType::Extern => Ref::Extern(None),
            HeapType::Func => Ref::Func(None),
            ty => unreachable!("not a heap type: {ty:?}"),
        }
    }

    /// Is this a null reference?
    #[inline]
    pub fn is_null(&self) -> bool {
        match self {
            Ref::Any(None) | Ref::Extern(None) | Ref::Func(None) => true,
            Ref::Any(Some(_)) | Ref::Extern(Some(_)) | Ref::Func(Some(_)) => false,
        }
    }

    /// Is this a non-null reference?
    #[inline]
    pub fn is_non_null(&self) -> bool {
        !self.is_null()
    }

    /// Is this an `extern` reference?
    #[inline]
    pub fn is_extern(&self) -> bool {
        matches!(self, Ref::Extern(_))
    }

    /// Get the underlying `extern` reference, if any.
    ///
    /// Returns `None` if this `Ref` is not an `extern` reference, eg it is a
    /// `func` reference.
    ///
    /// Returns `Some(None)` if this `Ref` is a null `extern` reference.
    ///
    /// Returns `Some(Some(_))` if this `Ref` is a non-null `extern` reference.
    #[inline]
    pub fn as_extern(&self) -> Option<Option<&Rooted<ExternRef>>> {
        match self {
            Ref::Extern(e) => Some(e.as_ref()),
            _ => None,
        }
    }

    /// Get the underlying `extern` reference, panicking if this is a different
    /// kind of reference.
    ///
    /// Returns `None` if this `Ref` is a null `extern` reference.
    ///
    /// Returns `Some(_)` if this `Ref` is a non-null `extern` reference.
    #[inline]
    pub fn unwrap_extern(&self) -> Option<&Rooted<ExternRef>> {
        self.as_extern()
            .expect("Ref::unwrap_extern on non-extern reference")
    }

    /// Is this an `any` reference?
    #[inline]
    pub fn is_any(&self) -> bool {
        matches!(self, Ref::Any(_))
    }

    /// Get the underlying `any` reference, if any.
    ///
    /// Returns `None` if this `Ref` is not an `any` reference, eg it is a
    /// `func` reference.
    ///
    /// Returns `Some(None)` if this `Ref` is a null `any` reference.
    ///
    /// Returns `Some(Some(_))` if this `Ref` is a non-null `any` reference.
    #[inline]
    pub fn as_any(&self) -> Option<Option<&Rooted<AnyRef>>> {
        match self {
            Ref::Any(e) => Some(e.as_ref()),
            _ => None,
        }
    }

    /// Get the underlying `any` reference, panicking if this is a different
    /// kind of reference.
    ///
    /// Returns `None` if this `Ref` is a null `any` reference.
    ///
    /// Returns `Some(_)` if this `Ref` is a non-null `any` reference.
    #[inline]
    pub fn unwrap_any(&self) -> Option<&Rooted<AnyRef>> {
        self.as_any().expect("Ref::unwrap_any on non-any reference")
    }

    /// Is this a `func` reference?
    #[inline]
    pub fn is_func(&self) -> bool {
        matches!(self, Ref::Func(_))
    }

    /// Get the underlying `func` reference, if any.
    ///
    /// Returns `None` if this `Ref` is not an `func` reference, eg it is an
    /// `extern` reference.
    ///
    /// Returns `Some(None)` if this `Ref` is a null `func` reference.
    ///
    /// Returns `Some(Some(_))` if this `Ref` is a non-null `func` reference.
    #[inline]
    pub fn as_func(&self) -> Option<Option<&Func>> {
        match self {
            Ref::Func(f) => Some(f.as_ref()),
            _ => None,
        }
    }

    /// Get the underlying `func` reference, panicking if this is a different
    /// kind of reference.
    ///
    /// Returns `None` if this `Ref` is a null `func` reference.
    ///
    /// Returns `Some(_)` if this `Ref` is a non-null `func` reference.
    #[inline]
    pub fn unwrap_func(&self) -> Option<&Func> {
        self.as_func()
            .expect("Ref::unwrap_func on non-func reference")
    }

    /// Get the type of this reference.
    ///
    /// # Errors
    ///
    /// Return an error if this reference has been unrooted.
    ///
    /// # Panics
    ///
    /// Panics if this reference is associated with a different store.
    pub fn ty(&self, store: impl AsContext) -> Result<RefType> {
        self.load_ty(&store.as_context().0)
    }

    pub(crate) fn load_ty(&self, store: &StoreOpaque) -> Result<RefType> {
        assert!(self.comes_from_same_store(store));
        Ok(RefType::new(
            self.is_null(),
            // NB: We choose the most-specific heap type we can here and let
            // subtyping do its thing if callers are matching against a
            // `HeapType::Func`.
            match self {
                Ref::Extern(None) => HeapType::NoExtern,
                Ref::Extern(Some(_)) => HeapType::Extern,

                Ref::Func(None) => HeapType::NoFunc,
                Ref::Func(Some(f)) => HeapType::ConcreteFunc(f.load_ty(store)),

                Ref::Any(None) => HeapType::None,
                Ref::Any(Some(a)) => a._ty(store)?,
            },
        ))
    }

    /// Does this reference value match the given type?
    ///
    /// Returns an error if the underlying `Rooted` has been unrooted.
    ///
    /// # Panics
    ///
    /// Panics if this reference is not associated with the given store.
    pub fn matches_ty(&self, store: impl AsContext, ty: &RefType) -> Result<bool> {
        self._matches_ty(&store.as_context().0, ty)
    }

    pub(crate) fn _matches_ty(&self, store: &StoreOpaque, ty: &RefType) -> Result<bool> {
        assert!(self.comes_from_same_store(store));
        assert!(ty.comes_from_same_engine(store.engine()));
        if self.is_null() && !ty.is_nullable() {
            return Ok(false);
        }
        Ok(match (self, ty.heap_type()) {
            (Ref::Extern(_), HeapType::Extern) => true,
            (Ref::Extern(_), _) => false,

            (Ref::Func(_), HeapType::Func) => true,
            (Ref::Func(None), HeapType::NoFunc | HeapType::ConcreteFunc(_)) => true,
            (Ref::Func(Some(f)), HeapType::ConcreteFunc(func_ty)) => f._matches_ty(store, func_ty),
            (Ref::Func(_), _) => false,

            (Ref::Any(_), HeapType::Any) => true,
            (Ref::Any(Some(a)), HeapType::I31) => a._is_i31(store)?,
            (Ref::Any(Some(a)), HeapType::Struct) => a._is_struct(store)?,
            (Ref::Any(Some(a)), HeapType::ConcreteStruct(_ty)) => match a._as_struct(store)? {
                None => false,
                #[cfg_attr(not(feature = "gc"), allow(unreachable_patterns))]
                Some(s) => s._matches_ty(store, _ty)?,
            },
            (Ref::Any(Some(_)), HeapType::Eq) => todo!("eqref"),
            (Ref::Any(Some(a)), HeapType::Array) => a._is_array(store)?,
            (Ref::Any(Some(a)), HeapType::ConcreteArray(_ty)) => match a._as_array(store)? {
                None => false,
                #[cfg_attr(not(feature = "gc"), allow(unreachable_patterns))]
                Some(a) => a._matches_ty(store, _ty)?,
            },
            (
                Ref::Any(None),
                HeapType::None
                | HeapType::I31
                | HeapType::ConcreteStruct(_)
                | HeapType::Struct
                | HeapType::ConcreteArray(_)
                | HeapType::Array,
            ) => true,
            (Ref::Any(_), _) => false,
        })
    }

    pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, ty: &RefType) -> Result<()> {
        if !self.comes_from_same_store(store) {
            bail!("reference used with wrong store")
        }
        if !ty.comes_from_same_engine(store.engine()) {
            bail!("type used with wrong engine")
        }
        if self._matches_ty(store, ty)? {
            Ok(())
        } else {
            let actual_ty = self.load_ty(store)?;
            bail!("type mismatch: expected {ty}, found {actual_ty}")
        }
    }

    pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
        match self {
            Ref::Func(Some(f)) => f.comes_from_same_store(store),
            Ref::Func(None) => true,
            Ref::Extern(Some(x)) => x.comes_from_same_store(store),
            Ref::Extern(None) => true,
            Ref::Any(Some(a)) => a.comes_from_same_store(store),
            Ref::Any(None) => true,
        }
    }

    pub(crate) fn into_table_element(
        self,
        store: &mut StoreOpaque,
        ty: &RefType,
    ) -> Result<TableElement> {
        let mut store = AutoAssertNoGc::new(store);
        self.ensure_matches_ty(&store, &ty)
            .context("type mismatch: value does not match table element type")?;

        match (self, ty.heap_type().top()) {
            (Ref::Func(None), HeapType::Func) => {
                assert!(ty.is_nullable());
                Ok(TableElement::FuncRef(ptr::null_mut()))
            }
            (Ref::Func(Some(f)), HeapType::Func) => {
                debug_assert!(
                    f.comes_from_same_store(&store),
                    "checked in `ensure_matches_ty`"
                );
                Ok(TableElement::FuncRef(f.vm_func_ref(&mut store).as_ptr()))
            }

            (Ref::Extern(e), HeapType::Extern) => match e {
                None => {
                    assert!(ty.is_nullable());
                    Ok(TableElement::GcRef(None))
                }
                #[cfg_attr(not(feature = "gc"), allow(unreachable_patterns))]
                Some(e) => {
                    let gc_ref = e.try_clone_gc_ref(&mut store)?;
                    Ok(TableElement::GcRef(Some(gc_ref)))
                }
            },

            (Ref::Any(a), HeapType::Any) => match a {
                None => {
                    assert!(ty.is_nullable());
                    Ok(TableElement::GcRef(None))
                }
                #[cfg_attr(not(feature = "gc"), allow(unreachable_patterns))]
                Some(a) => {
                    let gc_ref = a.try_clone_gc_ref(&mut store)?;
                    Ok(TableElement::GcRef(Some(gc_ref)))
                }
            },

            _ => unreachable!("checked that the value matches the type above"),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn size_of_val() {
        // Try to keep tabs on the size of `Val` and make sure we don't grow its
        // size.
        assert_eq!(
            std::mem::size_of::<Val>(),
            if cfg!(any(
                target_arch = "x86_64",
                target_arch = "aarch64",
                target_arch = "riscv64",
                target_arch = "s390x"
            )) {
                24
            } else {
                panic!("unsupported architecture")
            }
        );
    }

    #[test]
    fn size_of_ref() {
        // Try to keep tabs on the size of `Ref` and make sure we don't grow its
        // size.
        assert_eq!(std::mem::size_of::<Ref>(), 24);
    }

    #[test]
    #[should_panic]
    fn val_matches_ty_wrong_engine() {
        let e1 = Engine::default();
        let e2 = Engine::default();

        let t1 = FuncType::new(&e1, None, None);
        let t2 = FuncType::new(&e2, None, None);

        let mut s1 = Store::new(&e1, ());
        let f = Func::new(&mut s1, t1.clone(), |_caller, _args, _results| Ok(()));

        // Should panic.
        let _ = Val::FuncRef(Some(f)).matches_ty(
            &s1,
            &ValType::Ref(RefType::new(true, HeapType::ConcreteFunc(t2))),
        );
    }

    #[test]
    #[should_panic]
    fn ref_matches_ty_wrong_engine() {
        let e1 = Engine::default();
        let e2 = Engine::default();

        let t1 = FuncType::new(&e1, None, None);
        let t2 = FuncType::new(&e2, None, None);

        let mut s1 = Store::new(&e1, ());
        let f = Func::new(&mut s1, t1.clone(), |_caller, _args, _results| Ok(()));

        // Should panic.
        let _ = Ref::Func(Some(f)).matches_ty(&s1, &RefType::new(true, HeapType::ConcreteFunc(t2)));
    }
}