wasmtime/runtime/types.rs
1use crate::prelude::*;
2use crate::runtime::Memory as RuntimeMemory;
3use crate::runtime::externals::Global as RuntimeGlobal;
4use crate::runtime::externals::Table as RuntimeTable;
5use crate::runtime::externals::Tag as RuntimeTag;
6use crate::{AsContextMut, Extern, Func, Val};
7use crate::{Engine, type_registry::RegisteredType};
8use core::fmt::{self, Display, Write};
9use wasmtime_environ::WasmExnType;
10use wasmtime_environ::{
11 EngineOrModuleTypeIndex, EntityType, Global, IndexType, Limits, Memory, ModuleTypes, Table,
12 Tag, TypeTrace, VMSharedTypeIndex, WasmArrayType, WasmCompositeInnerType, WasmCompositeType,
13 WasmFieldType, WasmFuncType, WasmHeapType, WasmRefType, WasmStorageType, WasmStructType,
14 WasmSubType, WasmValType,
15};
16
17pub(crate) mod matching;
18
19// Type Representations
20
21// Type attributes
22
23/// Indicator of whether a global value, struct's field, or array type's
24/// elements are mutable or not.
25#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
26pub enum Mutability {
27 /// The global value, struct field, or array elements are constant and the
28 /// value does not change.
29 Const,
30 /// The value of the global, struct field, or array elements can change over
31 /// time.
32 Var,
33}
34
35impl Mutability {
36 /// Is this constant?
37 #[inline]
38 pub fn is_const(&self) -> bool {
39 *self == Self::Const
40 }
41
42 /// Is this variable?
43 #[inline]
44 pub fn is_var(&self) -> bool {
45 *self == Self::Var
46 }
47}
48
49/// Indicator of whether a type is final or not.
50///
51/// Final types may not be the supertype of other types.
52#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
53pub enum Finality {
54 /// The associated type is final.
55 Final,
56 /// The associated type is not final.
57 NonFinal,
58}
59
60impl Finality {
61 /// Is this final?
62 #[inline]
63 pub fn is_final(&self) -> bool {
64 *self == Self::Final
65 }
66
67 /// Is this non-final?
68 #[inline]
69 pub fn is_non_final(&self) -> bool {
70 *self == Self::NonFinal
71 }
72}
73
74// Value Types
75
76/// A list of all possible value types in WebAssembly.
77///
78/// # Subtyping and Equality
79///
80/// `ValType` does not implement `Eq`, because reference types have a subtyping
81/// relationship, and so 99.99% of the time you actually want to check whether
82/// one type matches (i.e. is a subtype of) another type. You can use the
83/// [`ValType::matches`] and [`Val::matches_ty`][crate::Val::matches_ty] methods
84/// to perform these types of checks. If, however, you are in that 0.01%
85/// scenario where you need to check precise equality between types, you can use
86/// the [`ValType::eq`] method.
87#[derive(Clone, Hash)]
88pub enum ValType {
89 // NB: the ordering of variants here is intended to match the ordering in
90 // `wasmtime_environ::WasmType` to help improve codegen when converting.
91 //
92 /// Signed 32 bit integer.
93 I32,
94 /// Signed 64 bit integer.
95 I64,
96 /// Floating point 32 bit integer.
97 F32,
98 /// Floating point 64 bit integer.
99 F64,
100 /// A 128 bit number.
101 V128,
102 /// An opaque reference to some type on the heap.
103 Ref(RefType),
104}
105
106impl fmt::Debug for ValType {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 fmt::Display::fmt(self, f)
109 }
110}
111
112impl Display for ValType {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 match self {
115 ValType::I32 => write!(f, "i32"),
116 ValType::I64 => write!(f, "i64"),
117 ValType::F32 => write!(f, "f32"),
118 ValType::F64 => write!(f, "f64"),
119 ValType::V128 => write!(f, "v128"),
120 ValType::Ref(r) => Display::fmt(r, f),
121 }
122 }
123}
124
125impl From<RefType> for ValType {
126 #[inline]
127 fn from(r: RefType) -> Self {
128 ValType::Ref(r)
129 }
130}
131
132impl ValType {
133 /// The `externref` type, aka `(ref null extern)`.
134 pub const EXTERNREF: Self = ValType::Ref(RefType::EXTERNREF);
135
136 /// The `nullexternref` type, aka `(ref null noextern)`.
137 pub const NULLEXTERNREF: Self = ValType::Ref(RefType::NULLEXTERNREF);
138
139 /// The `funcref` type, aka `(ref null func)`.
140 pub const FUNCREF: Self = ValType::Ref(RefType::FUNCREF);
141
142 /// The `nullfuncref` type, aka `(ref null nofunc)`.
143 pub const NULLFUNCREF: Self = ValType::Ref(RefType::NULLFUNCREF);
144
145 /// The `anyref` type, aka `(ref null any)`.
146 pub const ANYREF: Self = ValType::Ref(RefType::ANYREF);
147
148 /// The `eqref` type, aka `(ref null eq)`.
149 pub const EQREF: Self = ValType::Ref(RefType::EQREF);
150
151 /// The `i31ref` type, aka `(ref null i31)`.
152 pub const I31REF: Self = ValType::Ref(RefType::I31REF);
153
154 /// The `arrayref` type, aka `(ref null array)`.
155 pub const ARRAYREF: Self = ValType::Ref(RefType::ARRAYREF);
156
157 /// The `structref` type, aka `(ref null struct)`.
158 pub const STRUCTREF: Self = ValType::Ref(RefType::STRUCTREF);
159
160 /// The `nullref` type, aka `(ref null none)`.
161 pub const NULLREF: Self = ValType::Ref(RefType::NULLREF);
162
163 /// The `contref` type, aka `(ref null cont)`.
164 pub const CONTREF: Self = ValType::Ref(RefType::CONTREF);
165
166 /// The `nullcontref` type, aka. `(ref null nocont)`.
167 pub const NULLCONTREF: Self = ValType::Ref(RefType::NULLCONTREF);
168
169 /// The `exnref` type, aka `(ref null exn)`.
170 pub const EXNREF: Self = ValType::Ref(RefType::EXNREF);
171
172 /// The `nullexnref` type, aka `(ref null noexn)`.
173 pub const NULLEXNREF: Self = ValType::Ref(RefType::NULLEXNREF);
174
175 /// Returns true if `ValType` matches any of the numeric types. (e.g. `I32`,
176 /// `I64`, `F32`, `F64`).
177 #[inline]
178 pub fn is_num(&self) -> bool {
179 match self {
180 ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 => true,
181 _ => false,
182 }
183 }
184
185 /// Is this the `i32` type?
186 #[inline]
187 pub fn is_i32(&self) -> bool {
188 matches!(self, ValType::I32)
189 }
190
191 /// Is this the `i64` type?
192 #[inline]
193 pub fn is_i64(&self) -> bool {
194 matches!(self, ValType::I64)
195 }
196
197 /// Is this the `f32` type?
198 #[inline]
199 pub fn is_f32(&self) -> bool {
200 matches!(self, ValType::F32)
201 }
202
203 /// Is this the `f64` type?
204 #[inline]
205 pub fn is_f64(&self) -> bool {
206 matches!(self, ValType::F64)
207 }
208
209 /// Is this the `v128` type?
210 #[inline]
211 pub fn is_v128(&self) -> bool {
212 matches!(self, ValType::V128)
213 }
214
215 /// Returns true if `ValType` is any kind of reference type.
216 #[inline]
217 pub fn is_ref(&self) -> bool {
218 matches!(self, ValType::Ref(_))
219 }
220
221 /// Is this the `funcref` (aka `(ref null func)`) type?
222 #[inline]
223 pub fn is_funcref(&self) -> bool {
224 matches!(
225 self,
226 ValType::Ref(RefType {
227 is_nullable: true,
228 heap_type: HeapType::Func
229 })
230 )
231 }
232
233 /// Is this the `externref` (aka `(ref null extern)`) type?
234 #[inline]
235 pub fn is_externref(&self) -> bool {
236 matches!(
237 self,
238 ValType::Ref(RefType {
239 is_nullable: true,
240 heap_type: HeapType::Extern
241 })
242 )
243 }
244
245 /// Is this the `anyref` (aka `(ref null any)`) type?
246 #[inline]
247 pub fn is_anyref(&self) -> bool {
248 matches!(
249 self,
250 ValType::Ref(RefType {
251 is_nullable: true,
252 heap_type: HeapType::Any
253 })
254 )
255 }
256
257 /// Is this the `contref` (aka `(ref null cont)`) type?
258 #[inline]
259 pub fn is_contref(&self) -> bool {
260 matches!(
261 self,
262 ValType::Ref(RefType {
263 is_nullable: true,
264 heap_type: HeapType::Cont
265 })
266 )
267 }
268
269 /// Get the underlying reference type, if this value type is a reference
270 /// type.
271 #[inline]
272 pub fn as_ref(&self) -> Option<&RefType> {
273 match self {
274 ValType::Ref(r) => Some(r),
275 _ => None,
276 }
277 }
278
279 /// Get the underlying reference type, panicking if this value type is not a
280 /// reference type.
281 #[inline]
282 pub fn unwrap_ref(&self) -> &RefType {
283 self.as_ref()
284 .expect("ValType::unwrap_ref on a non-reference type")
285 }
286
287 /// Does this value type match the other type?
288 ///
289 /// That is, is this value type a subtype of the other?
290 ///
291 /// # Panics
292 ///
293 /// Panics if either type is associated with a different engine from the
294 /// other.
295 pub fn matches(&self, other: &ValType) -> bool {
296 match (self, other) {
297 (Self::I32, Self::I32) => true,
298 (Self::I64, Self::I64) => true,
299 (Self::F32, Self::F32) => true,
300 (Self::F64, Self::F64) => true,
301 (Self::V128, Self::V128) => true,
302 (Self::Ref(a), Self::Ref(b)) => a.matches(b),
303 (Self::I32, _)
304 | (Self::I64, _)
305 | (Self::F32, _)
306 | (Self::F64, _)
307 | (Self::V128, _)
308 | (Self::Ref(_), _) => false,
309 }
310 }
311
312 /// Is value type `a` precisely equal to value type `b`?
313 ///
314 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
315 /// are not exactly the same value type.
316 ///
317 /// # Panics
318 ///
319 /// Panics if either type is associated with a different engine.
320 pub fn eq(a: &Self, b: &Self) -> bool {
321 a.matches(b) && b.matches(a)
322 }
323
324 /// Is this a `VMGcRef` type that is not i31 and is not an uninhabited
325 /// bottom type?
326 #[inline]
327 pub(crate) fn is_vmgcref_type_and_points_to_object(&self) -> bool {
328 match self {
329 ValType::Ref(r) => r.is_vmgcref_type_and_points_to_object(),
330 ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => false,
331 }
332 }
333
334 pub(crate) fn ensure_matches(&self, engine: &Engine, other: &ValType) -> Result<()> {
335 if !self.comes_from_same_engine(engine) || !other.comes_from_same_engine(engine) {
336 bail!("type used with wrong engine");
337 }
338 if self.matches(other) {
339 Ok(())
340 } else {
341 bail!("type mismatch: expected {other}, found {self}")
342 }
343 }
344
345 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
346 match self {
347 Self::I32 | Self::I64 | Self::F32 | Self::F64 | Self::V128 => true,
348 Self::Ref(r) => r.comes_from_same_engine(engine),
349 }
350 }
351
352 pub(crate) fn to_wasm_type(&self) -> WasmValType {
353 match self {
354 Self::I32 => WasmValType::I32,
355 Self::I64 => WasmValType::I64,
356 Self::F32 => WasmValType::F32,
357 Self::F64 => WasmValType::F64,
358 Self::V128 => WasmValType::V128,
359 Self::Ref(r) => WasmValType::Ref(r.to_wasm_type()),
360 }
361 }
362
363 #[inline]
364 pub(crate) fn from_wasm_type(engine: &Engine, ty: &WasmValType) -> Self {
365 match ty {
366 WasmValType::I32 => Self::I32,
367 WasmValType::I64 => Self::I64,
368 WasmValType::F32 => Self::F32,
369 WasmValType::F64 => Self::F64,
370 WasmValType::V128 => Self::V128,
371 WasmValType::Ref(r) => Self::Ref(RefType::from_wasm_type(engine, r)),
372 }
373 }
374 /// Construct a default value. Returns None for non-nullable Ref types, which have no default.
375 pub fn default_value(&self) -> Option<Val> {
376 match self {
377 ValType::I32 => Some(Val::I32(0)),
378 ValType::I64 => Some(Val::I64(0)),
379 ValType::F32 => Some(Val::F32(0)),
380 ValType::F64 => Some(Val::F64(0)),
381 ValType::V128 => Some(Val::V128(0.into())),
382 ValType::Ref(r) => {
383 if r.is_nullable() {
384 Some(Val::null_ref(r.heap_type()))
385 } else {
386 None
387 }
388 }
389 }
390 }
391
392 pub(crate) fn into_registered_type(self) -> Option<RegisteredType> {
393 match self {
394 ValType::Ref(ty) => ty.into_registered_type(),
395 _ => None,
396 }
397 }
398}
399
400/// Opaque references to data in the Wasm heap or to host data.
401///
402/// # Subtyping and Equality
403///
404/// `RefType` does not implement `Eq`, because reference types have a subtyping
405/// relationship, and so 99.99% of the time you actually want to check whether
406/// one type matches (i.e. is a subtype of) another type. You can use the
407/// [`RefType::matches`] and [`Ref::matches_ty`][crate::Ref::matches_ty] methods
408/// to perform these types of checks. If, however, you are in that 0.01%
409/// scenario where you need to check precise equality between types, you can use
410/// the [`RefType::eq`] method.
411#[derive(Clone, Hash)]
412pub struct RefType {
413 is_nullable: bool,
414 heap_type: HeapType,
415}
416
417impl fmt::Debug for RefType {
418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 Display::fmt(self, f)
420 }
421}
422
423impl fmt::Display for RefType {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 write!(f, "(ref ")?;
426 if self.is_nullable() {
427 write!(f, "null ")?;
428 }
429 write!(f, "{})", self.heap_type())
430 }
431}
432
433impl RefType {
434 /// The `externref` type, aka `(ref null extern)`.
435 pub const EXTERNREF: Self = RefType {
436 is_nullable: true,
437 heap_type: HeapType::Extern,
438 };
439
440 /// The `nullexternref` type, aka `(ref null noextern)`.
441 pub const NULLEXTERNREF: Self = RefType {
442 is_nullable: true,
443 heap_type: HeapType::NoExtern,
444 };
445
446 /// The `funcref` type, aka `(ref null func)`.
447 pub const FUNCREF: Self = RefType {
448 is_nullable: true,
449 heap_type: HeapType::Func,
450 };
451
452 /// The `nullfuncref` type, aka `(ref null nofunc)`.
453 pub const NULLFUNCREF: Self = RefType {
454 is_nullable: true,
455 heap_type: HeapType::NoFunc,
456 };
457
458 /// The `anyref` type, aka `(ref null any)`.
459 pub const ANYREF: Self = RefType {
460 is_nullable: true,
461 heap_type: HeapType::Any,
462 };
463
464 /// The `eqref` type, aka `(ref null eq)`.
465 pub const EQREF: Self = RefType {
466 is_nullable: true,
467 heap_type: HeapType::Eq,
468 };
469
470 /// The `i31ref` type, aka `(ref null i31)`.
471 pub const I31REF: Self = RefType {
472 is_nullable: true,
473 heap_type: HeapType::I31,
474 };
475
476 /// The `arrayref` type, aka `(ref null array)`.
477 pub const ARRAYREF: Self = RefType {
478 is_nullable: true,
479 heap_type: HeapType::Array,
480 };
481
482 /// The `structref` type, aka `(ref null struct)`.
483 pub const STRUCTREF: Self = RefType {
484 is_nullable: true,
485 heap_type: HeapType::Struct,
486 };
487
488 /// The `nullref` type, aka `(ref null none)`.
489 pub const NULLREF: Self = RefType {
490 is_nullable: true,
491 heap_type: HeapType::None,
492 };
493
494 /// The `contref` type, aka `(ref null cont)`.
495 pub const CONTREF: Self = RefType {
496 is_nullable: true,
497 heap_type: HeapType::Cont,
498 };
499
500 /// The `nullcontref` type, aka `(ref null nocont)`.
501 pub const NULLCONTREF: Self = RefType {
502 is_nullable: true,
503 heap_type: HeapType::NoCont,
504 };
505
506 /// The `exnref` type, aka `(ref null exn)`.
507 pub const EXNREF: Self = RefType {
508 is_nullable: true,
509 heap_type: HeapType::Exn,
510 };
511
512 /// The `nullexnref` type, aka `(ref null noexn)`.
513 pub const NULLEXNREF: Self = RefType {
514 is_nullable: true,
515 heap_type: HeapType::NoExn,
516 };
517
518 /// Construct a new reference type.
519 pub fn new(is_nullable: bool, heap_type: HeapType) -> RefType {
520 RefType {
521 is_nullable,
522 heap_type,
523 }
524 }
525
526 /// Can this type of reference be null?
527 pub fn is_nullable(&self) -> bool {
528 self.is_nullable
529 }
530
531 /// The heap type that this is a reference to.
532 #[inline]
533 pub fn heap_type(&self) -> &HeapType {
534 &self.heap_type
535 }
536
537 /// Does this reference type match the other?
538 ///
539 /// That is, is this reference type a subtype of the other?
540 ///
541 /// # Panics
542 ///
543 /// Panics if either type is associated with a different engine from the
544 /// other.
545 pub fn matches(&self, other: &RefType) -> bool {
546 if self.is_nullable() && !other.is_nullable() {
547 return false;
548 }
549 self.heap_type().matches(other.heap_type())
550 }
551
552 /// Is reference type `a` precisely equal to reference type `b`?
553 ///
554 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
555 /// are not exactly the same reference type.
556 ///
557 /// # Panics
558 ///
559 /// Panics if either type is associated with a different engine.
560 pub fn eq(a: &RefType, b: &RefType) -> bool {
561 a.matches(b) && b.matches(a)
562 }
563
564 pub(crate) fn ensure_matches(&self, engine: &Engine, other: &RefType) -> Result<()> {
565 if !self.comes_from_same_engine(engine) || !other.comes_from_same_engine(engine) {
566 bail!("type used with wrong engine");
567 }
568 if self.matches(other) {
569 Ok(())
570 } else {
571 bail!("type mismatch: expected {other}, found {self}")
572 }
573 }
574
575 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
576 self.heap_type().comes_from_same_engine(engine)
577 }
578
579 pub(crate) fn to_wasm_type(&self) -> WasmRefType {
580 WasmRefType {
581 nullable: self.is_nullable(),
582 heap_type: self.heap_type().to_wasm_type(),
583 }
584 }
585
586 pub(crate) fn from_wasm_type(engine: &Engine, ty: &WasmRefType) -> RefType {
587 RefType {
588 is_nullable: ty.nullable,
589 heap_type: HeapType::from_wasm_type(engine, &ty.heap_type),
590 }
591 }
592
593 pub(crate) fn is_vmgcref_type_and_points_to_object(&self) -> bool {
594 self.heap_type().is_vmgcref_type_and_points_to_object()
595 }
596
597 pub(crate) fn into_registered_type(self) -> Option<RegisteredType> {
598 self.heap_type.into_registered_type()
599 }
600}
601
602/// The heap types that can Wasm can have references to.
603///
604/// # Subtyping Hierarchy
605///
606/// Wasm has three different heap type hierarchies:
607///
608/// 1. Function types
609/// 2. External types
610/// 3. Internal (struct and array) types
611/// 4. Exception types
612///
613/// Each hierarchy has a top type (the common supertype of which everything else
614/// in its hierarchy is a subtype of) and a bottom type (the common subtype of
615/// which everything else in its hierarchy is supertype of).
616///
617/// ## Function Types Hierarchy
618///
619/// The top of the function types hierarchy is `func`; the bottom is
620/// `nofunc`. In between are all the concrete function types.
621///
622/// ```text
623/// func
624/// / / \ \
625/// ,---------------- / \ -------------------------.
626/// / / \ \
627/// | ,---- -----------. |
628/// | | | |
629/// | | | |
630/// (func) (func (param i32)) (func (param i32 i32)) ...
631/// | | | |
632/// | | | |
633/// | `---. ,----------' |
634/// \ \ / /
635/// `---------------. \ / ,------------------------'
636/// \ \ / /
637/// nofunc
638/// ```
639///
640/// Additionally, some concrete function types are sub- or supertypes of other
641/// concrete function types, if that was declared in their definition. For
642/// simplicity, this isn't depicted in the diagram above.
643///
644/// ## External
645///
646/// The top of the external types hierarchy is `extern`; the bottom is
647/// `noextern`. There are no concrete types in this hierarchy.
648///
649/// ```text
650/// extern
651/// |
652/// noextern
653/// ```
654///
655/// ## Internal
656///
657/// The top of the internal types hierarchy is `any`; the bottom is `none`. The
658/// `eq` type is the common supertype of all types that can be compared for
659/// equality. The `struct` and `array` types are the common supertypes of all
660/// concrete struct and array types respectively. The `i31` type represents
661/// unboxed 31-bit integers.
662///
663/// ```text
664/// any
665/// / | \
666/// ,----------------------------' | `--------------------------.
667/// / | \
668/// | .--------' |
669/// | | |
670/// | struct array
671/// | / | \ / | \
672/// i31 ,-----' | '-----. ,-----' | `-----.
673/// | / | \ / | \
674/// | | | | | | |
675/// | (struct) (struct i32) ... (array i32) (array i64) ...
676/// | | | | | | |
677/// | \ | / \ | /
678/// \ `-----. | ,-----' `-----. | ,-----'
679/// \ \ | / \ | /
680/// \ \ | / \ | /
681/// \ \| / \| /
682/// \ |/ |/
683/// \ | |
684/// \ | /
685/// \ '--------. /
686/// \ | /
687/// `--------------------. | ,-----------------------'
688/// \ | /
689/// none
690/// ```
691///
692/// Additionally, concrete struct and array types can be subtypes of other
693/// concrete struct and array types respectively, if that was declared in their
694/// definitions. Once again, this is omitted from the above diagram for
695/// simplicity.
696///
697/// ## Exceptions
698///
699/// The top of the exception types hierarchy is `exn`; the bottom is
700/// `noexn`. At the WebAssembly level, there are no concrete types in
701/// this hierarchy. However, internally we do reify a heap type for
702/// each tag, similar to how continuation objects work.
703///
704/// ```text
705/// exn
706/// / | \
707/// (exn $t) ...
708/// \ | /
709/// noexn
710/// ```
711///
712/// # Subtyping and Equality
713///
714/// `HeapType` does not implement `Eq`, because heap types have a subtyping
715/// relationship, and so 99.99% of the time you actually want to check whether
716/// one type matches (i.e. is a subtype of) another type. You can use the
717/// [`HeapType::matches`] method to perform these types of checks. If, however,
718/// you are in that 0.01% scenario where you need to check precise equality
719/// between types, you can use the [`HeapType::eq`] method.
720#[derive(Debug, Clone, Hash)]
721pub enum HeapType {
722 /// The abstract `extern` heap type represents external host data.
723 ///
724 /// This is the top type for the external type hierarchy, and therefore is
725 /// the common supertype of all external reference types.
726 Extern,
727
728 /// The abstract `noextern` heap type represents the null external
729 /// reference.
730 ///
731 /// This is the bottom type for the external type hierarchy, and therefore
732 /// is the common subtype of all external reference types.
733 NoExtern,
734
735 /// The abstract `func` heap type represents a reference to any kind of
736 /// function.
737 ///
738 /// This is the top type for the function references type hierarchy, and is
739 /// therefore a supertype of every function reference.
740 Func,
741
742 /// A reference to a function of a specific, concrete type.
743 ///
744 /// These are subtypes of `func` and supertypes of `nofunc`.
745 ConcreteFunc(FuncType),
746
747 /// The abstract `nofunc` heap type represents the null function reference.
748 ///
749 /// This is the bottom type for the function references type hierarchy, and
750 /// therefore `nofunc` is a subtype of all function reference types.
751 NoFunc,
752
753 /// The abstract `any` heap type represents all internal Wasm data.
754 ///
755 /// This is the top type of the internal type hierarchy, and is therefore a
756 /// supertype of all internal types (such as `eq`, `i31`, `struct`s, and
757 /// `array`s).
758 Any,
759
760 /// The abstract `eq` heap type represenets all internal Wasm references
761 /// that can be compared for equality.
762 ///
763 /// This is a subtype of `any` and a supertype of `i31`, `array`, `struct`,
764 /// and `none` heap types.
765 Eq,
766
767 /// The `i31` heap type represents unboxed 31-bit integers.
768 ///
769 /// This is a subtype of `any` and `eq`, and a supertype of `none`.
770 I31,
771
772 /// The abstract `array` heap type represents a reference to any kind of
773 /// array.
774 ///
775 /// This is a subtype of `any` and `eq`, and a supertype of all concrete
776 /// array types, as well as a supertype of the abstract `none` heap type.
777 Array,
778
779 /// A reference to an array of a specific, concrete type.
780 ///
781 /// These are subtypes of the `array` heap type (therefore also a subtype of
782 /// `any` and `eq`) and supertypes of the `none` heap type.
783 ConcreteArray(ArrayType),
784
785 /// The abstract `struct` heap type represents a reference to any kind of
786 /// struct.
787 ///
788 /// This is a subtype of `any` and `eq`, and a supertype of all concrete
789 /// struct types, as well as a supertype of the abstract `none` heap type.
790 Struct,
791
792 /// A reference to an struct of a specific, concrete type.
793 ///
794 /// These are subtypes of the `struct` heap type (therefore also a subtype
795 /// of `any` and `eq`) and supertypes of the `none` heap type.
796 ConcreteStruct(StructType),
797
798 /// The abstract `exn` heap type represents a reference to any
799 /// kind of exception.
800 ///
801 /// This is a supertype of the internal concrete exception heap
802 /// types and the `noexn` heap type.
803 Exn,
804
805 /// A concrete exception object with a specific tag.
806 ///
807 /// These are internal, not exposed at the Wasm level, but useful
808 /// in our implementation and host API. These are subtypes of
809 /// `exn` and supertypes of `noexn`.
810 ConcreteExn(ExnType),
811
812 /// A reference to a continuation of a specific, concrete type.
813 ///
814 /// These are subtypes of `cont` and supertypes of `nocont`.
815 ConcreteCont(ContType),
816
817 /// The `cont` heap type represents a reference to any kind of continuation.
818 ///
819 /// This is the top type for the continuation objects type hierarchy, and is
820 /// therefore a supertype of every continuation object.
821 Cont,
822
823 /// The `nocont` heap type represents the null continuation object.
824 ///
825 /// This is the bottom type for the continuation objects type hierarchy, and
826 /// therefore `nocont` is a subtype of all continuation object types.
827 NoCont,
828
829 /// The abstract `none` heap type represents the null internal reference.
830 ///
831 /// This is the bottom type for the internal type hierarchy, and therefore
832 /// `none` is a subtype of internal types.
833 None,
834
835 /// The `noexn` heap type represents the null exception object.
836 ///
837 /// This is the bottom type for the exception objects type hierarchy.
838 NoExn,
839}
840
841impl Display for HeapType {
842 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
843 match self {
844 HeapType::Extern => write!(f, "extern"),
845 HeapType::NoExtern => write!(f, "noextern"),
846 HeapType::Func => write!(f, "func"),
847 HeapType::NoFunc => write!(f, "nofunc"),
848 HeapType::Any => write!(f, "any"),
849 HeapType::Eq => write!(f, "eq"),
850 HeapType::I31 => write!(f, "i31"),
851 HeapType::Array => write!(f, "array"),
852 HeapType::Struct => write!(f, "struct"),
853 HeapType::None => write!(f, "none"),
854 HeapType::ConcreteFunc(ty) => write!(f, "(concrete func {:?})", ty.type_index()),
855 HeapType::ConcreteArray(ty) => write!(f, "(concrete array {:?})", ty.type_index()),
856 HeapType::ConcreteStruct(ty) => write!(f, "(concrete struct {:?})", ty.type_index()),
857 HeapType::ConcreteCont(ty) => write!(f, "(concrete cont {:?})", ty.type_index()),
858 HeapType::ConcreteExn(ty) => write!(f, "(concrete exn {:?})", ty.type_index()),
859 HeapType::Cont => write!(f, "cont"),
860 HeapType::NoCont => write!(f, "nocont"),
861 HeapType::Exn => write!(f, "exn"),
862 HeapType::NoExn => write!(f, "noexn"),
863 }
864 }
865}
866
867impl From<FuncType> for HeapType {
868 #[inline]
869 fn from(f: FuncType) -> Self {
870 HeapType::ConcreteFunc(f)
871 }
872}
873
874impl From<ArrayType> for HeapType {
875 #[inline]
876 fn from(a: ArrayType) -> Self {
877 HeapType::ConcreteArray(a)
878 }
879}
880
881impl From<StructType> for HeapType {
882 #[inline]
883 fn from(s: StructType) -> Self {
884 HeapType::ConcreteStruct(s)
885 }
886}
887
888impl From<ContType> for HeapType {
889 #[inline]
890 fn from(f: ContType) -> Self {
891 HeapType::ConcreteCont(f)
892 }
893}
894
895impl From<ExnType> for HeapType {
896 #[inline]
897 fn from(e: ExnType) -> Self {
898 HeapType::ConcreteExn(e)
899 }
900}
901
902impl HeapType {
903 /// Is this the abstract `extern` heap type?
904 pub fn is_extern(&self) -> bool {
905 matches!(self, HeapType::Extern)
906 }
907
908 /// Is this the abstract `func` heap type?
909 pub fn is_func(&self) -> bool {
910 matches!(self, HeapType::Func)
911 }
912
913 /// Is this the abstract `nofunc` heap type?
914 pub fn is_no_func(&self) -> bool {
915 matches!(self, HeapType::NoFunc)
916 }
917
918 /// Is this the abstract `any` heap type?
919 pub fn is_any(&self) -> bool {
920 matches!(self, HeapType::Any)
921 }
922
923 /// Is this the abstract `i31` heap type?
924 pub fn is_i31(&self) -> bool {
925 matches!(self, HeapType::I31)
926 }
927
928 /// Is this the abstract `none` heap type?
929 pub fn is_none(&self) -> bool {
930 matches!(self, HeapType::None)
931 }
932
933 /// Is this the abstract `cont` heap type?
934 pub fn is_cont(&self) -> bool {
935 matches!(self, HeapType::Cont)
936 }
937
938 /// Is this the abstract `exn` heap type?
939 pub fn is_exn(&self) -> bool {
940 matches!(self, HeapType::Exn)
941 }
942
943 /// Is this the abstract `noexn` heap type?
944 pub fn is_no_exn(&self) -> bool {
945 matches!(self, HeapType::NoExn)
946 }
947
948 /// Is this an abstract type?
949 ///
950 /// Types that are not abstract are concrete, user-defined types.
951 pub fn is_abstract(&self) -> bool {
952 !self.is_concrete()
953 }
954
955 /// Is this a concrete, user-defined heap type?
956 ///
957 /// Types that are not concrete, user-defined types are abstract types.
958 #[inline]
959 pub fn is_concrete(&self) -> bool {
960 matches!(
961 self,
962 HeapType::ConcreteFunc(_)
963 | HeapType::ConcreteArray(_)
964 | HeapType::ConcreteStruct(_)
965 | HeapType::ConcreteCont(_)
966 | HeapType::ConcreteExn(_)
967 )
968 }
969
970 /// Is this a concrete, user-defined function type?
971 pub fn is_concrete_func(&self) -> bool {
972 matches!(self, HeapType::ConcreteFunc(_))
973 }
974
975 /// Get the underlying concrete, user-defined function type, if any.
976 ///
977 /// Returns `None` if this is not a concrete function type.
978 pub fn as_concrete_func(&self) -> Option<&FuncType> {
979 match self {
980 HeapType::ConcreteFunc(f) => Some(f),
981 _ => None,
982 }
983 }
984
985 /// Get the underlying concrete, user-defined type, panicking if this is not
986 /// a concrete function type.
987 pub fn unwrap_concrete_func(&self) -> &FuncType {
988 self.as_concrete_func().unwrap()
989 }
990
991 /// Is this a concrete, user-defined array type?
992 pub fn is_concrete_array(&self) -> bool {
993 matches!(self, HeapType::ConcreteArray(_))
994 }
995
996 /// Get the underlying concrete, user-defined array type, if any.
997 ///
998 /// Returns `None` for if this is not a concrete array type.
999 pub fn as_concrete_array(&self) -> Option<&ArrayType> {
1000 match self {
1001 HeapType::ConcreteArray(f) => Some(f),
1002 _ => None,
1003 }
1004 }
1005
1006 /// Get the underlying concrete, user-defined type, panicking if this is not
1007 /// a concrete array type.
1008 pub fn unwrap_concrete_array(&self) -> &ArrayType {
1009 self.as_concrete_array().unwrap()
1010 }
1011
1012 /// Is this a concrete, user-defined continuation type?
1013 pub fn is_concrete_cont(&self) -> bool {
1014 matches!(self, HeapType::ConcreteCont(_))
1015 }
1016
1017 /// Get the underlying concrete, user-defined continuation type, if any.
1018 ///
1019 /// Returns `None` if this is not a concrete continuation type.
1020 pub fn as_concrete_cont(&self) -> Option<&ContType> {
1021 match self {
1022 HeapType::ConcreteCont(f) => Some(f),
1023 _ => None,
1024 }
1025 }
1026
1027 /// Is this a concrete, user-defined struct type?
1028 pub fn is_concrete_struct(&self) -> bool {
1029 matches!(self, HeapType::ConcreteStruct(_))
1030 }
1031
1032 /// Get the underlying concrete, user-defined struct type, if any.
1033 ///
1034 /// Returns `None` for if this is not a concrete struct type.
1035 pub fn as_concrete_struct(&self) -> Option<&StructType> {
1036 match self {
1037 HeapType::ConcreteStruct(f) => Some(f),
1038 _ => None,
1039 }
1040 }
1041
1042 /// Get the underlying concrete, user-defined type, panicking if this is not
1043 /// a concrete continuation type.
1044 pub fn unwrap_concrete_cont(&self) -> &ContType {
1045 self.as_concrete_cont().unwrap()
1046 }
1047
1048 /// Get the underlying concrete, user-defined type, panicking if this is not
1049 /// a concrete struct type.
1050 pub fn unwrap_concrete_struct(&self) -> &StructType {
1051 self.as_concrete_struct().unwrap()
1052 }
1053
1054 /// Is this a concrete, user-defined exception type?
1055 pub fn is_concrete_exn(&self) -> bool {
1056 matches!(self, HeapType::ConcreteExn(_))
1057 }
1058
1059 /// Get the underlying concrete, user-defined exception type, if any.
1060 ///
1061 /// Returns `None` if this is not a concrete exception type.
1062 pub fn as_concrete_exn(&self) -> Option<&ExnType> {
1063 match self {
1064 HeapType::ConcreteExn(e) => Some(e),
1065 _ => None,
1066 }
1067 }
1068
1069 /// Get the top type of this heap type's type hierarchy.
1070 ///
1071 /// The returned heap type is a supertype of all types in this heap type's
1072 /// type hierarchy.
1073 #[inline]
1074 pub fn top(&self) -> HeapType {
1075 match self {
1076 HeapType::Func | HeapType::ConcreteFunc(_) | HeapType::NoFunc => HeapType::Func,
1077
1078 HeapType::Extern | HeapType::NoExtern => HeapType::Extern,
1079
1080 HeapType::Any
1081 | HeapType::Eq
1082 | HeapType::I31
1083 | HeapType::Array
1084 | HeapType::ConcreteArray(_)
1085 | HeapType::Struct
1086 | HeapType::ConcreteStruct(_)
1087 | HeapType::None => HeapType::Any,
1088
1089 HeapType::Cont | HeapType::ConcreteCont(_) | HeapType::NoCont => HeapType::Cont,
1090
1091 HeapType::Exn | HeapType::ConcreteExn(_) | HeapType::NoExn => HeapType::Exn,
1092 }
1093 }
1094
1095 /// Is this the top type within its type hierarchy?
1096 #[inline]
1097 pub fn is_top(&self) -> bool {
1098 match self {
1099 HeapType::Any | HeapType::Extern | HeapType::Func | HeapType::Cont | HeapType::Exn => {
1100 true
1101 }
1102 _ => false,
1103 }
1104 }
1105
1106 /// Get the bottom type of this heap type's type hierarchy.
1107 ///
1108 /// The returned heap type is a subtype of all types in this heap type's
1109 /// type hierarchy.
1110 #[inline]
1111 pub fn bottom(&self) -> HeapType {
1112 match self {
1113 HeapType::Extern | HeapType::NoExtern => HeapType::NoExtern,
1114
1115 HeapType::Func | HeapType::ConcreteFunc(_) | HeapType::NoFunc => HeapType::NoFunc,
1116
1117 HeapType::Any
1118 | HeapType::Eq
1119 | HeapType::I31
1120 | HeapType::Array
1121 | HeapType::ConcreteArray(_)
1122 | HeapType::Struct
1123 | HeapType::ConcreteStruct(_)
1124 | HeapType::None => HeapType::None,
1125
1126 HeapType::Cont | HeapType::ConcreteCont(_) | HeapType::NoCont => HeapType::NoCont,
1127
1128 HeapType::Exn | HeapType::ConcreteExn(_) | HeapType::NoExn => HeapType::NoExn,
1129 }
1130 }
1131
1132 /// Is this the bottom type within its type hierarchy?
1133 #[inline]
1134 pub fn is_bottom(&self) -> bool {
1135 match self {
1136 HeapType::None
1137 | HeapType::NoExtern
1138 | HeapType::NoFunc
1139 | HeapType::NoCont
1140 | HeapType::NoExn => true,
1141 _ => false,
1142 }
1143 }
1144
1145 /// Does this heap type match the other heap type?
1146 ///
1147 /// That is, is this heap type a subtype of the other?
1148 ///
1149 /// # Panics
1150 ///
1151 /// Panics if either type is associated with a different engine from the
1152 /// other.
1153 pub fn matches(&self, other: &HeapType) -> bool {
1154 match (self, other) {
1155 (HeapType::Extern, HeapType::Extern) => true,
1156 (HeapType::Extern, _) => false,
1157
1158 (HeapType::NoExtern, HeapType::NoExtern | HeapType::Extern) => true,
1159 (HeapType::NoExtern, _) => false,
1160
1161 (HeapType::NoFunc, HeapType::NoFunc | HeapType::ConcreteFunc(_) | HeapType::Func) => {
1162 true
1163 }
1164 (HeapType::NoFunc, _) => false,
1165
1166 (HeapType::ConcreteFunc(_), HeapType::Func) => true,
1167 (HeapType::ConcreteFunc(a), HeapType::ConcreteFunc(b)) => {
1168 assert!(a.comes_from_same_engine(b.engine()));
1169 a.engine()
1170 .signatures()
1171 .is_subtype(a.type_index(), b.type_index())
1172 }
1173 (HeapType::ConcreteFunc(_), _) => false,
1174
1175 (HeapType::Func, HeapType::Func) => true,
1176 (HeapType::Func, _) => false,
1177
1178 (HeapType::Cont, HeapType::Cont) => true,
1179 (HeapType::Cont, _) => false,
1180
1181 (HeapType::NoCont, HeapType::NoCont | HeapType::ConcreteCont(_) | HeapType::Cont) => {
1182 true
1183 }
1184 (HeapType::NoCont, _) => false,
1185
1186 (HeapType::ConcreteCont(_), HeapType::Cont) => true,
1187 (HeapType::ConcreteCont(a), HeapType::ConcreteCont(b)) => a.matches(b),
1188 (HeapType::ConcreteCont(_), _) => false,
1189
1190 (
1191 HeapType::None,
1192 HeapType::None
1193 | HeapType::ConcreteArray(_)
1194 | HeapType::Array
1195 | HeapType::ConcreteStruct(_)
1196 | HeapType::Struct
1197 | HeapType::I31
1198 | HeapType::Eq
1199 | HeapType::Any,
1200 ) => true,
1201 (HeapType::None, _) => false,
1202
1203 (HeapType::ConcreteArray(_), HeapType::Array | HeapType::Eq | HeapType::Any) => true,
1204 (HeapType::ConcreteArray(a), HeapType::ConcreteArray(b)) => {
1205 assert!(a.comes_from_same_engine(b.engine()));
1206 a.engine()
1207 .signatures()
1208 .is_subtype(a.type_index(), b.type_index())
1209 }
1210 (HeapType::ConcreteArray(_), _) => false,
1211
1212 (HeapType::Array, HeapType::Array | HeapType::Eq | HeapType::Any) => true,
1213 (HeapType::Array, _) => false,
1214
1215 (HeapType::ConcreteStruct(_), HeapType::Struct | HeapType::Eq | HeapType::Any) => true,
1216 (HeapType::ConcreteStruct(a), HeapType::ConcreteStruct(b)) => {
1217 assert!(a.comes_from_same_engine(b.engine()));
1218 a.engine()
1219 .signatures()
1220 .is_subtype(a.type_index(), b.type_index())
1221 }
1222 (HeapType::ConcreteStruct(_), _) => false,
1223
1224 (HeapType::Struct, HeapType::Struct | HeapType::Eq | HeapType::Any) => true,
1225 (HeapType::Struct, _) => false,
1226
1227 (HeapType::I31, HeapType::I31 | HeapType::Eq | HeapType::Any) => true,
1228 (HeapType::I31, _) => false,
1229
1230 (HeapType::Eq, HeapType::Eq | HeapType::Any) => true,
1231 (HeapType::Eq, _) => false,
1232
1233 (HeapType::Any, HeapType::Any) => true,
1234 (HeapType::Any, _) => false,
1235
1236 (HeapType::NoExn, HeapType::Exn | HeapType::ConcreteExn(_) | HeapType::NoExn) => true,
1237 (HeapType::NoExn, _) => true,
1238
1239 (HeapType::ConcreteExn(_), HeapType::Exn) => true,
1240 (HeapType::ConcreteExn(a), HeapType::ConcreteExn(b)) => a.matches(b),
1241 (HeapType::ConcreteExn(_), _) => false,
1242
1243 (HeapType::Exn, HeapType::Exn) => true,
1244 (HeapType::Exn, _) => false,
1245 }
1246 }
1247
1248 /// Is heap type `a` precisely equal to heap type `b`?
1249 ///
1250 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
1251 /// are not exactly the same heap type.
1252 ///
1253 /// # Panics
1254 ///
1255 /// Panics if either type is associated with a different engine from the
1256 /// other.
1257 pub fn eq(a: &HeapType, b: &HeapType) -> bool {
1258 a.matches(b) && b.matches(a)
1259 }
1260
1261 pub(crate) fn ensure_matches(&self, engine: &Engine, other: &HeapType) -> Result<()> {
1262 if !self.comes_from_same_engine(engine) || !other.comes_from_same_engine(engine) {
1263 bail!("type used with wrong engine");
1264 }
1265 if self.matches(other) {
1266 Ok(())
1267 } else {
1268 bail!("type mismatch: expected {other}, found {self}");
1269 }
1270 }
1271
1272 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
1273 match self {
1274 HeapType::Extern
1275 | HeapType::NoExtern
1276 | HeapType::Func
1277 | HeapType::NoFunc
1278 | HeapType::Any
1279 | HeapType::Eq
1280 | HeapType::I31
1281 | HeapType::Array
1282 | HeapType::Struct
1283 | HeapType::Cont
1284 | HeapType::NoCont
1285 | HeapType::Exn
1286 | HeapType::NoExn
1287 | HeapType::None => true,
1288 HeapType::ConcreteFunc(ty) => ty.comes_from_same_engine(engine),
1289 HeapType::ConcreteArray(ty) => ty.comes_from_same_engine(engine),
1290 HeapType::ConcreteStruct(ty) => ty.comes_from_same_engine(engine),
1291 HeapType::ConcreteCont(ty) => ty.comes_from_same_engine(engine),
1292 HeapType::ConcreteExn(ty) => ty.comes_from_same_engine(engine),
1293 }
1294 }
1295
1296 pub(crate) fn to_wasm_type(&self) -> WasmHeapType {
1297 match self {
1298 HeapType::Extern => WasmHeapType::Extern,
1299 HeapType::NoExtern => WasmHeapType::NoExtern,
1300 HeapType::Func => WasmHeapType::Func,
1301 HeapType::NoFunc => WasmHeapType::NoFunc,
1302 HeapType::Any => WasmHeapType::Any,
1303 HeapType::Eq => WasmHeapType::Eq,
1304 HeapType::I31 => WasmHeapType::I31,
1305 HeapType::Array => WasmHeapType::Array,
1306 HeapType::Struct => WasmHeapType::Struct,
1307 HeapType::None => WasmHeapType::None,
1308 HeapType::ConcreteFunc(f) => {
1309 WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::Engine(f.type_index()))
1310 }
1311 HeapType::ConcreteArray(a) => {
1312 WasmHeapType::ConcreteArray(EngineOrModuleTypeIndex::Engine(a.type_index()))
1313 }
1314 HeapType::ConcreteStruct(a) => {
1315 WasmHeapType::ConcreteStruct(EngineOrModuleTypeIndex::Engine(a.type_index()))
1316 }
1317 HeapType::Cont => WasmHeapType::Cont,
1318 HeapType::NoCont => WasmHeapType::NoCont,
1319 HeapType::ConcreteCont(c) => {
1320 WasmHeapType::ConcreteCont(EngineOrModuleTypeIndex::Engine(c.type_index()))
1321 }
1322 HeapType::Exn => WasmHeapType::Exn,
1323 HeapType::NoExn => WasmHeapType::NoExn,
1324 HeapType::ConcreteExn(e) => {
1325 WasmHeapType::ConcreteExn(EngineOrModuleTypeIndex::Engine(e.type_index()))
1326 }
1327 }
1328 }
1329
1330 pub(crate) fn from_wasm_type(engine: &Engine, ty: &WasmHeapType) -> HeapType {
1331 match ty {
1332 WasmHeapType::Extern => HeapType::Extern,
1333 WasmHeapType::NoExtern => HeapType::NoExtern,
1334 WasmHeapType::Func => HeapType::Func,
1335 WasmHeapType::NoFunc => HeapType::NoFunc,
1336 WasmHeapType::Any => HeapType::Any,
1337 WasmHeapType::Eq => HeapType::Eq,
1338 WasmHeapType::I31 => HeapType::I31,
1339 WasmHeapType::Array => HeapType::Array,
1340 WasmHeapType::Struct => HeapType::Struct,
1341 WasmHeapType::None => HeapType::None,
1342 WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::Engine(idx)) => {
1343 HeapType::ConcreteFunc(FuncType::from_shared_type_index(engine, *idx))
1344 }
1345 WasmHeapType::ConcreteArray(EngineOrModuleTypeIndex::Engine(idx)) => {
1346 HeapType::ConcreteArray(ArrayType::from_shared_type_index(engine, *idx))
1347 }
1348 WasmHeapType::ConcreteStruct(EngineOrModuleTypeIndex::Engine(idx)) => {
1349 HeapType::ConcreteStruct(StructType::from_shared_type_index(engine, *idx))
1350 }
1351
1352 WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::Module(_))
1353 | WasmHeapType::ConcreteFunc(EngineOrModuleTypeIndex::RecGroup(_))
1354 | WasmHeapType::ConcreteArray(EngineOrModuleTypeIndex::Module(_))
1355 | WasmHeapType::ConcreteArray(EngineOrModuleTypeIndex::RecGroup(_))
1356 | WasmHeapType::ConcreteStruct(EngineOrModuleTypeIndex::Module(_))
1357 | WasmHeapType::ConcreteStruct(EngineOrModuleTypeIndex::RecGroup(_))
1358 | WasmHeapType::ConcreteCont(EngineOrModuleTypeIndex::Module(_))
1359 | WasmHeapType::ConcreteCont(EngineOrModuleTypeIndex::RecGroup(_))
1360 | WasmHeapType::ConcreteExn(EngineOrModuleTypeIndex::Module(_))
1361 | WasmHeapType::ConcreteExn(EngineOrModuleTypeIndex::RecGroup(_)) => {
1362 panic!("HeapType::from_wasm_type on non-canonicalized-for-runtime-usage heap type")
1363 }
1364 WasmHeapType::Cont => HeapType::Cont,
1365 WasmHeapType::NoCont => HeapType::NoCont,
1366 WasmHeapType::ConcreteCont(EngineOrModuleTypeIndex::Engine(idx)) => {
1367 HeapType::ConcreteCont(ContType::from_shared_type_index(engine, *idx))
1368 }
1369 WasmHeapType::Exn => HeapType::Exn,
1370 WasmHeapType::NoExn => HeapType::NoExn,
1371 WasmHeapType::ConcreteExn(EngineOrModuleTypeIndex::Engine(idx)) => {
1372 HeapType::ConcreteExn(ExnType::from_shared_type_index(engine, *idx))
1373 }
1374 }
1375 }
1376
1377 pub(crate) fn as_registered_type(&self) -> Option<&RegisteredType> {
1378 match self {
1379 HeapType::ConcreteCont(c) => Some(&c.registered_type),
1380 HeapType::ConcreteFunc(f) => Some(&f.registered_type),
1381 HeapType::ConcreteArray(a) => Some(&a.registered_type),
1382 HeapType::ConcreteStruct(a) => Some(&a.registered_type),
1383 HeapType::ConcreteExn(e) => Some(&e.registered_type),
1384
1385 HeapType::Extern
1386 | HeapType::NoExtern
1387 | HeapType::Func
1388 | HeapType::NoFunc
1389 | HeapType::Any
1390 | HeapType::Eq
1391 | HeapType::I31
1392 | HeapType::Array
1393 | HeapType::Struct
1394 | HeapType::Cont
1395 | HeapType::NoCont
1396 | HeapType::Exn
1397 | HeapType::NoExn
1398 | HeapType::None => None,
1399 }
1400 }
1401
1402 #[inline]
1403 pub(crate) fn is_vmgcref_type(&self) -> bool {
1404 match self.top() {
1405 Self::Any | Self::Extern | Self::Exn => true,
1406 Self::Func => false,
1407 Self::Cont => false,
1408 ty => unreachable!("not a top type: {ty:?}"),
1409 }
1410 }
1411
1412 /// Is this a `VMGcRef` type that is not i31 and is not an uninhabited
1413 /// bottom type?
1414 #[inline]
1415 pub(crate) fn is_vmgcref_type_and_points_to_object(&self) -> bool {
1416 self.is_vmgcref_type()
1417 && !matches!(
1418 self,
1419 HeapType::I31 | HeapType::NoExtern | HeapType::NoFunc | HeapType::None
1420 )
1421 }
1422
1423 pub(crate) fn into_registered_type(self) -> Option<RegisteredType> {
1424 use HeapType::*;
1425 match self {
1426 ConcreteFunc(ty) => Some(ty.registered_type),
1427 ConcreteArray(ty) => Some(ty.registered_type),
1428 ConcreteStruct(ty) => Some(ty.registered_type),
1429 ConcreteCont(ty) => Some(ty.registered_type),
1430 ConcreteExn(ty) => Some(ty.registered_type),
1431 Extern | NoExtern | Func | NoFunc | Any | Eq | I31 | Array | Struct | Cont | NoCont
1432 | Exn | NoExn | None => Option::None,
1433 }
1434 }
1435}
1436
1437// External Types
1438
1439/// A list of all possible types which can be externally referenced from a
1440/// WebAssembly module.
1441///
1442/// This list can be found in [`ImportType`] or [`ExportType`], so these types
1443/// can either be imported or exported.
1444#[derive(Debug, Clone)]
1445pub enum ExternType {
1446 /// This external type is the type of a WebAssembly function.
1447 Func(FuncType),
1448 /// This external type is the type of a WebAssembly global.
1449 Global(GlobalType),
1450 /// This external type is the type of a WebAssembly table.
1451 Table(TableType),
1452 /// This external type is the type of a WebAssembly memory.
1453 Memory(MemoryType),
1454 /// This external type is the type of a WebAssembly tag.
1455 Tag(TagType),
1456}
1457
1458macro_rules! extern_type_accessors {
1459 ($(($variant:ident($ty:ty) $get:ident $unwrap:ident))*) => ($(
1460 /// Attempt to return the underlying type of this external type,
1461 /// returning `None` if it is a different type.
1462 pub fn $get(&self) -> Option<&$ty> {
1463 if let ExternType::$variant(e) = self {
1464 Some(e)
1465 } else {
1466 None
1467 }
1468 }
1469
1470 /// Returns the underlying descriptor of this [`ExternType`], panicking
1471 /// if it is a different type.
1472 ///
1473 /// # Panics
1474 ///
1475 /// Panics if `self` is not of the right type.
1476 pub fn $unwrap(&self) -> &$ty {
1477 self.$get().expect(concat!("expected ", stringify!($ty)))
1478 }
1479 )*)
1480}
1481
1482impl ExternType {
1483 extern_type_accessors! {
1484 (Func(FuncType) func unwrap_func)
1485 (Global(GlobalType) global unwrap_global)
1486 (Table(TableType) table unwrap_table)
1487 (Memory(MemoryType) memory unwrap_memory)
1488 (Tag(TagType) tag unwrap_tag)
1489 }
1490
1491 pub(crate) fn from_wasmtime(
1492 engine: &Engine,
1493 types: &ModuleTypes,
1494 ty: &EntityType,
1495 ) -> ExternType {
1496 match ty {
1497 EntityType::Function(idx) => match idx {
1498 EngineOrModuleTypeIndex::Engine(e) => {
1499 FuncType::from_shared_type_index(engine, *e).into()
1500 }
1501 EngineOrModuleTypeIndex::Module(m) => {
1502 let subty = &types[*m];
1503 debug_assert!(subty.is_canonicalized_for_runtime_usage());
1504 // subty.canonicalize_for_runtime_usage(&mut |idx| {
1505 // signatures.shared_type(idx).unwrap()
1506 // });
1507 FuncType::from_wasm_func_type(
1508 engine,
1509 subty.is_final,
1510 subty.supertype,
1511 subty.unwrap_func().clone(),
1512 )
1513 .into()
1514 }
1515 EngineOrModuleTypeIndex::RecGroup(_) => unreachable!(),
1516 },
1517 EntityType::Global(ty) => GlobalType::from_wasmtime_global(engine, ty).into(),
1518 EntityType::Memory(ty) => MemoryType::from_wasmtime_memory(ty).into(),
1519 EntityType::Table(ty) => TableType::from_wasmtime_table(engine, ty).into(),
1520 EntityType::Tag(ty) => TagType::from_wasmtime_tag(engine, ty).into(),
1521 }
1522 }
1523 /// Construct a default value, if possible, for the underlying type.
1524 pub fn default_value(&self, store: impl AsContextMut) -> Result<Extern> {
1525 match self {
1526 ExternType::Func(func_ty) => func_ty.default_value(store).map(Extern::Func),
1527 ExternType::Global(global_ty) => global_ty.default_value(store).map(Extern::Global),
1528 ExternType::Table(table_ty) => table_ty.default_value(store).map(Extern::Table),
1529 ExternType::Memory(mem_ty) => mem_ty.default_value(store).map(Extern::Memory),
1530 ExternType::Tag(tag_ty) => tag_ty.default_value(store).map(Extern::Tag),
1531 }
1532 }
1533}
1534
1535impl From<FuncType> for ExternType {
1536 fn from(ty: FuncType) -> ExternType {
1537 ExternType::Func(ty)
1538 }
1539}
1540
1541impl From<GlobalType> for ExternType {
1542 fn from(ty: GlobalType) -> ExternType {
1543 ExternType::Global(ty)
1544 }
1545}
1546
1547impl From<MemoryType> for ExternType {
1548 fn from(ty: MemoryType) -> ExternType {
1549 ExternType::Memory(ty)
1550 }
1551}
1552
1553impl From<TableType> for ExternType {
1554 fn from(ty: TableType) -> ExternType {
1555 ExternType::Table(ty)
1556 }
1557}
1558
1559impl From<TagType> for ExternType {
1560 fn from(ty: TagType) -> ExternType {
1561 ExternType::Tag(ty)
1562 }
1563}
1564
1565/// The storage type of a `struct` field or `array` element.
1566///
1567/// This is either a packed 8- or -16 bit integer, or else it is some unpacked
1568/// Wasm value type.
1569#[derive(Clone, Hash)]
1570pub enum StorageType {
1571 /// `i8`, an 8-bit integer.
1572 I8,
1573 /// `i16`, a 16-bit integer.
1574 I16,
1575 /// A value type.
1576 ValType(ValType),
1577}
1578
1579impl fmt::Display for StorageType {
1580 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1581 match self {
1582 StorageType::I8 => write!(f, "i8"),
1583 StorageType::I16 => write!(f, "i16"),
1584 StorageType::ValType(ty) => fmt::Display::fmt(ty, f),
1585 }
1586 }
1587}
1588
1589impl From<ValType> for StorageType {
1590 #[inline]
1591 fn from(v: ValType) -> Self {
1592 StorageType::ValType(v)
1593 }
1594}
1595
1596impl From<RefType> for StorageType {
1597 #[inline]
1598 fn from(r: RefType) -> Self {
1599 StorageType::ValType(r.into())
1600 }
1601}
1602
1603impl StorageType {
1604 /// Is this an `i8`?
1605 #[inline]
1606 pub fn is_i8(&self) -> bool {
1607 matches!(self, Self::I8)
1608 }
1609
1610 /// Is this an `i16`?
1611 #[inline]
1612 pub fn is_i16(&self) -> bool {
1613 matches!(self, Self::I16)
1614 }
1615
1616 /// Is this a Wasm value type?
1617 #[inline]
1618 pub fn is_val_type(&self) -> bool {
1619 matches!(self, Self::I16)
1620 }
1621
1622 /// Get this storage type's underlying value type, if any.
1623 ///
1624 /// Returns `None` if this storage type is not a value type.
1625 #[inline]
1626 pub fn as_val_type(&self) -> Option<&ValType> {
1627 match self {
1628 Self::ValType(v) => Some(v),
1629 _ => None,
1630 }
1631 }
1632
1633 /// Get this storage type's underlying value type, panicking if it is not a
1634 /// value type.
1635 pub fn unwrap_val_type(&self) -> &ValType {
1636 self.as_val_type().unwrap()
1637 }
1638
1639 /// Unpack this (possibly packed) storage type into a full `ValType`.
1640 ///
1641 /// If this is a `StorageType::ValType`, then the inner `ValType` is
1642 /// returned as-is.
1643 ///
1644 /// If this is a packed `StorageType::I8` or `StorageType::I16, then a
1645 /// `ValType::I32` is returned.
1646 pub fn unpack(&self) -> &ValType {
1647 match self {
1648 StorageType::I8 | StorageType::I16 => &ValType::I32,
1649 StorageType::ValType(ty) => ty,
1650 }
1651 }
1652
1653 /// Does this field type match the other field type?
1654 ///
1655 /// That is, is this field type a subtype of the other field type?
1656 ///
1657 /// # Panics
1658 ///
1659 /// Panics if either type is associated with a different engine from the
1660 /// other.
1661 pub fn matches(&self, other: &Self) -> bool {
1662 match (self, other) {
1663 (StorageType::I8, StorageType::I8) => true,
1664 (StorageType::I8, _) => false,
1665 (StorageType::I16, StorageType::I16) => true,
1666 (StorageType::I16, _) => false,
1667 (StorageType::ValType(a), StorageType::ValType(b)) => a.matches(b),
1668 (StorageType::ValType(_), _) => false,
1669 }
1670 }
1671
1672 /// Is field type `a` precisely equal to field type `b`?
1673 ///
1674 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
1675 /// are not exactly the same field type.
1676 ///
1677 /// # Panics
1678 ///
1679 /// Panics if either type is associated with a different engine from the
1680 /// other.
1681 pub fn eq(a: &Self, b: &Self) -> bool {
1682 match (a, b) {
1683 (StorageType::I8, StorageType::I8) => true,
1684 (StorageType::I8, _) => false,
1685 (StorageType::I16, StorageType::I16) => true,
1686 (StorageType::I16, _) => false,
1687 (StorageType::ValType(a), StorageType::ValType(b)) => ValType::eq(a, b),
1688 (StorageType::ValType(_), _) => false,
1689 }
1690 }
1691
1692 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
1693 match self {
1694 StorageType::I8 | StorageType::I16 => true,
1695 StorageType::ValType(v) => v.comes_from_same_engine(engine),
1696 }
1697 }
1698
1699 pub(crate) fn from_wasm_storage_type(engine: &Engine, ty: &WasmStorageType) -> Self {
1700 match ty {
1701 WasmStorageType::I8 => Self::I8,
1702 WasmStorageType::I16 => Self::I16,
1703 WasmStorageType::Val(v) => ValType::from_wasm_type(engine, &v).into(),
1704 }
1705 }
1706
1707 pub(crate) fn to_wasm_storage_type(&self) -> WasmStorageType {
1708 match self {
1709 Self::I8 => WasmStorageType::I8,
1710 Self::I16 => WasmStorageType::I16,
1711 Self::ValType(v) => WasmStorageType::Val(v.to_wasm_type()),
1712 }
1713 }
1714
1715 /// The byte size of this type, if it has a defined size in the spec.
1716 ///
1717 /// See
1718 /// https://webassembly.github.io/gc/core/syntax/types.html#bitwidth-fieldtype
1719 /// and
1720 /// https://webassembly.github.io/gc/core/syntax/types.html#bitwidth-valtype
1721 #[cfg(feature = "gc")]
1722 pub(crate) fn data_byte_size(&self) -> Option<u32> {
1723 match self {
1724 StorageType::I8 => Some(1),
1725 StorageType::I16 => Some(2),
1726 StorageType::ValType(ValType::I32 | ValType::F32) => Some(4),
1727 StorageType::ValType(ValType::I64 | ValType::F64) => Some(8),
1728 StorageType::ValType(ValType::V128) => Some(16),
1729 StorageType::ValType(ValType::Ref(_)) => None,
1730 }
1731 }
1732}
1733
1734/// The type of a `struct` field or an `array`'s elements.
1735///
1736/// This is a pair of both the field's storage type and its mutability
1737/// (i.e. whether the field can be updated or not).
1738#[derive(Clone, Hash)]
1739pub struct FieldType {
1740 mutability: Mutability,
1741 element_type: StorageType,
1742}
1743
1744impl fmt::Display for FieldType {
1745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 if self.mutability.is_var() {
1747 write!(f, "(mut {})", self.element_type)
1748 } else {
1749 fmt::Display::fmt(&self.element_type, f)
1750 }
1751 }
1752}
1753
1754impl FieldType {
1755 /// Construct a new field type from the given parts.
1756 #[inline]
1757 pub fn new(mutability: Mutability, element_type: StorageType) -> Self {
1758 Self {
1759 mutability,
1760 element_type,
1761 }
1762 }
1763
1764 /// Get whether or not this field type is mutable.
1765 #[inline]
1766 pub fn mutability(&self) -> Mutability {
1767 self.mutability
1768 }
1769
1770 /// Get this field type's storage type.
1771 #[inline]
1772 pub fn element_type(&self) -> &StorageType {
1773 &self.element_type
1774 }
1775
1776 /// Does this field type match the other field type?
1777 ///
1778 /// That is, is this field type a subtype of the other field type?
1779 ///
1780 /// # Panics
1781 ///
1782 /// Panics if either type is associated with a different engine from the
1783 /// other.
1784 pub fn matches(&self, other: &Self) -> bool {
1785 // Our storage type must match `other`'s storage type and either
1786 //
1787 // 1. Both field types are immutable, or
1788 //
1789 // 2. Both field types are mutable and `other`'s storage type must match
1790 // ours, i.e. the storage types are exactly the same.
1791 use Mutability as M;
1792 match (self.mutability, other.mutability) {
1793 // Case 1
1794 (M::Const, M::Const) => self.element_type.matches(&other.element_type),
1795 // Case 2
1796 (M::Var, M::Var) => StorageType::eq(&self.element_type, &other.element_type),
1797 // Does not match.
1798 _ => false,
1799 }
1800 }
1801
1802 /// Is field type `a` precisely equal to field type `b`?
1803 ///
1804 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
1805 /// are not exactly the same field type.
1806 ///
1807 /// # Panics
1808 ///
1809 /// Panics if either type is associated with a different engine from the
1810 /// other.
1811 pub fn eq(a: &Self, b: &Self) -> bool {
1812 a.matches(b) && b.matches(a)
1813 }
1814
1815 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
1816 self.element_type.comes_from_same_engine(engine)
1817 }
1818
1819 pub(crate) fn from_wasm_field_type(engine: &Engine, ty: &WasmFieldType) -> Self {
1820 Self {
1821 mutability: if ty.mutable {
1822 Mutability::Var
1823 } else {
1824 Mutability::Const
1825 },
1826 element_type: StorageType::from_wasm_storage_type(engine, &ty.element_type),
1827 }
1828 }
1829
1830 pub(crate) fn to_wasm_field_type(&self) -> WasmFieldType {
1831 WasmFieldType {
1832 element_type: self.element_type.to_wasm_storage_type(),
1833 mutable: matches!(self.mutability, Mutability::Var),
1834 }
1835 }
1836}
1837
1838/// The type of a WebAssembly struct.
1839///
1840/// WebAssembly structs are a static, fixed-length, ordered sequence of
1841/// fields. Fields are named by index, not an identifier. Each field is mutable
1842/// or constant and stores unpacked [`Val`][crate::Val]s or packed 8-/16-bit
1843/// integers.
1844///
1845/// # Subtyping and Equality
1846///
1847/// `StructType` does not implement `Eq`, because reference types have a
1848/// subtyping relationship, and so 99.99% of the time you actually want to check
1849/// whether one type matches (i.e. is a subtype of) another type. You can use
1850/// the [`StructType::matches`] method to perform these types of checks. If,
1851/// however, you are in that 0.01% scenario where you need to check precise
1852/// equality between types, you can use the [`StructType::eq`] method.
1853//
1854// TODO: Once we have struct values, update above docs with a reference to the
1855// future `Struct::matches_ty` method
1856#[derive(Debug, Clone, Hash)]
1857pub struct StructType {
1858 registered_type: RegisteredType,
1859}
1860
1861impl fmt::Display for StructType {
1862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1863 write!(f, "(struct")?;
1864 for field in self.fields() {
1865 write!(f, " (field {field})")?;
1866 }
1867 write!(f, ")")?;
1868 Ok(())
1869 }
1870}
1871
1872impl StructType {
1873 /// Construct a new `StructType` with the given field types.
1874 ///
1875 /// This `StructType` will be final and without a supertype.
1876 ///
1877 /// The result will be associated with the given engine, and attempts to use
1878 /// it with other engines will panic (for example, checking whether it is a
1879 /// subtype of another struct type that is associated with a different
1880 /// engine).
1881 ///
1882 /// Returns an error if the number of fields exceeds the implementation
1883 /// limit.
1884 ///
1885 /// # Panics
1886 ///
1887 /// Panics if any given field type is not associated with the given engine.
1888 pub fn new(engine: &Engine, fields: impl IntoIterator<Item = FieldType>) -> Result<Self> {
1889 Self::with_finality_and_supertype(engine, Finality::Final, None, fields)
1890 }
1891
1892 /// Construct a new `StructType` with the given finality, supertype, and
1893 /// fields.
1894 ///
1895 /// The result will be associated with the given engine, and attempts to use
1896 /// it with other engines will panic (for example, checking whether it is a
1897 /// subtype of another struct type that is associated with a different
1898 /// engine).
1899 ///
1900 /// Returns an error if the number of fields exceeds the implementation
1901 /// limit, if the supertype is final, or if this type does not match the
1902 /// supertype.
1903 ///
1904 /// # Panics
1905 ///
1906 /// Panics if any given field type is not associated with the given engine.
1907 pub fn with_finality_and_supertype(
1908 engine: &Engine,
1909 finality: Finality,
1910 supertype: Option<&Self>,
1911 fields: impl IntoIterator<Item = FieldType>,
1912 ) -> Result<Self> {
1913 let fields = fields.into_iter();
1914
1915 let mut wasmtime_fields = Vec::with_capacity({
1916 let size_hint = fields.size_hint();
1917 let cap = size_hint.1.unwrap_or(size_hint.0);
1918 // Only reserve space if we have a supertype, as that is the only time
1919 // that this vec is used.
1920 supertype.is_some() as usize * cap
1921 });
1922
1923 // Same as in `FuncType::new`: we must prevent any `RegisteredType`s
1924 // from being reclaimed while constructing this struct type.
1925 let mut registrations = smallvec::SmallVec::<[_; 4]>::new();
1926
1927 let fields = fields
1928 .map(|ty: FieldType| {
1929 assert!(ty.comes_from_same_engine(engine));
1930
1931 if supertype.is_some() {
1932 wasmtime_fields.push(ty.clone());
1933 }
1934
1935 if let Some(r) = ty.element_type.as_val_type().and_then(|v| v.as_ref()) {
1936 if let Some(r) = r.heap_type().as_registered_type() {
1937 registrations.push(r.clone());
1938 }
1939 }
1940
1941 ty.to_wasm_field_type()
1942 })
1943 .collect();
1944
1945 if let Some(supertype) = supertype {
1946 ensure!(
1947 supertype.finality().is_non_final(),
1948 "cannot create a subtype of a final supertype"
1949 );
1950 ensure!(
1951 Self::fields_match(wasmtime_fields.into_iter(), supertype.fields()),
1952 "struct fields must match their supertype's fields"
1953 );
1954 }
1955
1956 Self::from_wasm_struct_type(
1957 engine,
1958 finality.is_final(),
1959 false,
1960 supertype.map(|ty| ty.type_index().into()),
1961 WasmStructType { fields },
1962 )
1963 }
1964
1965 /// Get the engine that this struct type is associated with.
1966 pub fn engine(&self) -> &Engine {
1967 self.registered_type.engine()
1968 }
1969
1970 /// Get the finality of this struct type.
1971 pub fn finality(&self) -> Finality {
1972 match self.registered_type.is_final {
1973 true => Finality::Final,
1974 false => Finality::NonFinal,
1975 }
1976 }
1977
1978 /// Get the supertype of this struct type, if any.
1979 pub fn supertype(&self) -> Option<Self> {
1980 self.registered_type
1981 .supertype
1982 .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
1983 }
1984
1985 /// Get the `i`th field type.
1986 ///
1987 /// Returns `None` if `i` is out of bounds.
1988 pub fn field(&self, i: usize) -> Option<FieldType> {
1989 let engine = self.engine();
1990 self.as_wasm_struct_type()
1991 .fields
1992 .get(i)
1993 .map(|ty| FieldType::from_wasm_field_type(engine, ty))
1994 }
1995
1996 /// Returns the list of field types for this function.
1997 #[inline]
1998 pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldType> + '_ {
1999 let engine = self.engine();
2000 self.as_wasm_struct_type()
2001 .fields
2002 .iter()
2003 .map(|ty| FieldType::from_wasm_field_type(engine, ty))
2004 }
2005
2006 /// Does this struct type match the other struct type?
2007 ///
2008 /// That is, is this function type a subtype of the other struct type?
2009 ///
2010 /// # Panics
2011 ///
2012 /// Panics if either type is associated with a different engine from the
2013 /// other.
2014 pub fn matches(&self, other: &StructType) -> bool {
2015 assert!(self.comes_from_same_engine(other.engine()));
2016
2017 self.engine()
2018 .signatures()
2019 .is_subtype(self.type_index(), other.type_index())
2020 }
2021
2022 fn fields_match(
2023 a: impl ExactSizeIterator<Item = FieldType>,
2024 b: impl ExactSizeIterator<Item = FieldType>,
2025 ) -> bool {
2026 a.len() >= b.len() && a.zip(b).all(|(a, b)| a.matches(&b))
2027 }
2028
2029 /// Is struct type `a` precisely equal to struct type `b`?
2030 ///
2031 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
2032 /// are not exactly the same struct type.
2033 ///
2034 /// # Panics
2035 ///
2036 /// Panics if either type is associated with a different engine from the
2037 /// other.
2038 pub fn eq(a: &StructType, b: &StructType) -> bool {
2039 assert!(a.comes_from_same_engine(b.engine()));
2040 a.type_index() == b.type_index()
2041 }
2042
2043 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
2044 Engine::same(self.registered_type().engine(), engine)
2045 }
2046
2047 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
2048 self.registered_type().index()
2049 }
2050
2051 pub(crate) fn as_wasm_struct_type(&self) -> &WasmStructType {
2052 self.registered_type().unwrap_struct()
2053 }
2054
2055 pub(crate) fn registered_type(&self) -> &RegisteredType {
2056 &self.registered_type
2057 }
2058
2059 /// Construct a `StructType` from a `WasmStructType`.
2060 ///
2061 /// This method should only be used when something has already registered --
2062 /// and is *keeping registered* -- any other concrete Wasm types referenced
2063 /// by the given `WasmStructType`.
2064 ///
2065 /// For example, this method may be called to convert an struct type from
2066 /// within a Wasm module's `ModuleTypes` since the Wasm module itself is
2067 /// holding a strong reference to all of its types, including any `(ref null
2068 /// <index>)` types used as the element type for this struct type.
2069 pub(crate) fn from_wasm_struct_type(
2070 engine: &Engine,
2071 is_final: bool,
2072 is_shared: bool,
2073 supertype: Option<EngineOrModuleTypeIndex>,
2074 ty: WasmStructType,
2075 ) -> Result<StructType> {
2076 const MAX_FIELDS: usize = 10_000;
2077 let fields_len = ty.fields.len();
2078 ensure!(
2079 fields_len <= MAX_FIELDS,
2080 "attempted to define a struct type with {fields_len} fields, but \
2081 that is more than the maximum supported number of fields \
2082 ({MAX_FIELDS})",
2083 );
2084
2085 let ty = RegisteredType::new(
2086 engine,
2087 WasmSubType {
2088 is_final,
2089 supertype,
2090 composite_type: WasmCompositeType {
2091 shared: is_shared,
2092 inner: WasmCompositeInnerType::Struct(ty),
2093 },
2094 },
2095 );
2096 Ok(Self {
2097 registered_type: ty,
2098 })
2099 }
2100
2101 pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> StructType {
2102 let ty = RegisteredType::root(engine, index);
2103 Self::from_registered_type(ty)
2104 }
2105
2106 pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
2107 debug_assert!(registered_type.is_struct());
2108 Self { registered_type }
2109 }
2110}
2111
2112/// The type of a WebAssembly array.
2113///
2114/// WebAssembly arrays are dynamically-sized, but not resizable. They contain
2115/// either unpacked [`Val`][crate::Val]s or packed 8-/16-bit integers.
2116///
2117/// # Subtyping and Equality
2118///
2119/// `ArrayType` does not implement `Eq`, because reference types have a
2120/// subtyping relationship, and so 99.99% of the time you actually want to check
2121/// whether one type matches (i.e. is a subtype of) another type. You can use
2122/// the [`ArrayType::matches`] method to perform these types of checks. If,
2123/// however, you are in that 0.01% scenario where you need to check precise
2124/// equality between types, you can use the [`ArrayType::eq`] method.
2125//
2126// TODO: Once we have array values, update above docs with a reference to the
2127// future `Array::matches_ty` method
2128#[derive(Debug, Clone, Hash)]
2129pub struct ArrayType {
2130 registered_type: RegisteredType,
2131}
2132
2133impl fmt::Display for ArrayType {
2134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2135 let field_ty = self.field_type();
2136 write!(f, "(array (field {field_ty}))")?;
2137 Ok(())
2138 }
2139}
2140
2141impl ArrayType {
2142 /// Construct a new `ArrayType` with the given field type's mutability and
2143 /// storage type.
2144 ///
2145 /// The new `ArrayType` will be final and without a supertype.
2146 ///
2147 /// The result will be associated with the given engine, and attempts to use
2148 /// it with other engines will panic (for example, checking whether it is a
2149 /// subtype of another array type that is associated with a different
2150 /// engine).
2151 ///
2152 /// # Panics
2153 ///
2154 /// Panics if the given field type is not associated with the given engine.
2155 pub fn new(engine: &Engine, field_type: FieldType) -> Self {
2156 Self::with_finality_and_supertype(engine, Finality::Final, None, field_type)
2157 .expect("cannot fail without a supertype")
2158 }
2159
2160 /// Construct a new `StructType` with the given finality, supertype, and
2161 /// fields.
2162 ///
2163 /// The result will be associated with the given engine, and attempts to use
2164 /// it with other engines will panic (for example, checking whether it is a
2165 /// subtype of another struct type that is associated with a different
2166 /// engine).
2167 ///
2168 /// Returns an error if the supertype is final, or if this type does not
2169 /// match the supertype.
2170 ///
2171 /// # Panics
2172 ///
2173 /// Panics if the given field type is not associated with the given engine.
2174 pub fn with_finality_and_supertype(
2175 engine: &Engine,
2176 finality: Finality,
2177 supertype: Option<&Self>,
2178 field_type: FieldType,
2179 ) -> Result<Self> {
2180 if let Some(supertype) = supertype {
2181 assert!(supertype.comes_from_same_engine(engine));
2182 ensure!(
2183 supertype.finality().is_non_final(),
2184 "cannot create a subtype of a final supertype"
2185 );
2186 ensure!(
2187 field_type.matches(&supertype.field_type()),
2188 "array field type must match its supertype's field type"
2189 );
2190 }
2191
2192 // Same as in `FuncType::new`: we must prevent any `RegisteredType` in
2193 // `field_type` from being reclaimed while constructing this array type.
2194 let _registration = field_type
2195 .element_type
2196 .as_val_type()
2197 .and_then(|v| v.as_ref())
2198 .and_then(|r| r.heap_type().as_registered_type());
2199
2200 assert!(field_type.comes_from_same_engine(engine));
2201 let wasm_ty = WasmArrayType(field_type.to_wasm_field_type());
2202
2203 Ok(Self::from_wasm_array_type(
2204 engine,
2205 finality.is_final(),
2206 supertype.map(|ty| ty.type_index().into()),
2207 wasm_ty,
2208 ))
2209 }
2210
2211 /// Get the engine that this array type is associated with.
2212 pub fn engine(&self) -> &Engine {
2213 self.registered_type.engine()
2214 }
2215
2216 /// Get the finality of this array type.
2217 pub fn finality(&self) -> Finality {
2218 match self.registered_type.is_final {
2219 true => Finality::Final,
2220 false => Finality::NonFinal,
2221 }
2222 }
2223
2224 /// Get the supertype of this array type, if any.
2225 pub fn supertype(&self) -> Option<Self> {
2226 self.registered_type
2227 .supertype
2228 .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
2229 }
2230
2231 /// Get this array's underlying field type.
2232 ///
2233 /// The field type contains information about both this array type's
2234 /// mutability and the storage type used for its elements.
2235 pub fn field_type(&self) -> FieldType {
2236 FieldType::from_wasm_field_type(self.engine(), &self.as_wasm_array_type().0)
2237 }
2238
2239 /// Get this array type's mutability and whether its instances' elements can
2240 /// be updated or not.
2241 ///
2242 /// This is a convenience method providing a short-hand for
2243 /// `my_array_type.field_type().mutability()`.
2244 pub fn mutability(&self) -> Mutability {
2245 if self.as_wasm_array_type().0.mutable {
2246 Mutability::Var
2247 } else {
2248 Mutability::Const
2249 }
2250 }
2251
2252 /// Get the storage type used for this array type's elements.
2253 ///
2254 /// This is a convenience method providing a short-hand for
2255 /// `my_array_type.field_type().element_type()`.
2256 pub fn element_type(&self) -> StorageType {
2257 StorageType::from_wasm_storage_type(
2258 self.engine(),
2259 &self.registered_type.unwrap_array().0.element_type,
2260 )
2261 }
2262
2263 /// Does this array type match the other array type?
2264 ///
2265 /// That is, is this function type a subtype of the other array type?
2266 ///
2267 /// # Panics
2268 ///
2269 /// Panics if either type is associated with a different engine from the
2270 /// other.
2271 pub fn matches(&self, other: &ArrayType) -> bool {
2272 assert!(self.comes_from_same_engine(other.engine()));
2273
2274 self.engine()
2275 .signatures()
2276 .is_subtype(self.type_index(), other.type_index())
2277 }
2278
2279 /// Is array type `a` precisely equal to array type `b`?
2280 ///
2281 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
2282 /// are not exactly the same array type.
2283 ///
2284 /// # Panics
2285 ///
2286 /// Panics if either type is associated with a different engine from the
2287 /// other.
2288 pub fn eq(a: &ArrayType, b: &ArrayType) -> bool {
2289 assert!(a.comes_from_same_engine(b.engine()));
2290 a.type_index() == b.type_index()
2291 }
2292
2293 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
2294 Engine::same(self.registered_type.engine(), engine)
2295 }
2296
2297 #[cfg(feature = "gc")]
2298 pub(crate) fn registered_type(&self) -> &RegisteredType {
2299 &self.registered_type
2300 }
2301
2302 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
2303 self.registered_type.index()
2304 }
2305
2306 pub(crate) fn as_wasm_array_type(&self) -> &WasmArrayType {
2307 self.registered_type.unwrap_array()
2308 }
2309
2310 /// Construct a `ArrayType` from a `WasmArrayType`.
2311 ///
2312 /// This method should only be used when something has already registered --
2313 /// and is *keeping registered* -- any other concrete Wasm types referenced
2314 /// by the given `WasmArrayType`.
2315 ///
2316 /// For example, this method may be called to convert an array type from
2317 /// within a Wasm module's `ModuleTypes` since the Wasm module itself is
2318 /// holding a strong reference to all of its types, including any `(ref null
2319 /// <index>)` types used as the element type for this array type.
2320 pub(crate) fn from_wasm_array_type(
2321 engine: &Engine,
2322 is_final: bool,
2323 supertype: Option<EngineOrModuleTypeIndex>,
2324 ty: WasmArrayType,
2325 ) -> ArrayType {
2326 let ty = RegisteredType::new(
2327 engine,
2328 WasmSubType {
2329 is_final,
2330 supertype,
2331 composite_type: WasmCompositeType {
2332 shared: false,
2333 inner: WasmCompositeInnerType::Array(ty),
2334 },
2335 },
2336 );
2337 Self {
2338 registered_type: ty,
2339 }
2340 }
2341
2342 pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ArrayType {
2343 let ty = RegisteredType::root(engine, index);
2344 Self::from_registered_type(ty)
2345 }
2346
2347 pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
2348 debug_assert!(registered_type.is_array());
2349 Self { registered_type }
2350 }
2351}
2352
2353/// The type of a WebAssembly function.
2354///
2355/// WebAssembly functions can have 0 or more parameters and results.
2356///
2357/// # Subtyping and Equality
2358///
2359/// `FuncType` does not implement `Eq`, because reference types have a subtyping
2360/// relationship, and so 99.99% of the time you actually want to check whether
2361/// one type matches (i.e. is a subtype of) another type. You can use the
2362/// [`FuncType::matches`] and [`Func::matches_ty`][crate::Func::matches_ty]
2363/// methods to perform these types of checks. If, however, you are in that 0.01%
2364/// scenario where you need to check precise equality between types, you can use
2365/// the [`FuncType::eq`] method.
2366#[derive(Debug, Clone, Hash)]
2367pub struct FuncType {
2368 registered_type: RegisteredType,
2369}
2370
2371impl Display for FuncType {
2372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2373 write!(f, "(type (func")?;
2374 if self.params().len() > 0 {
2375 write!(f, " (param")?;
2376 for p in self.params() {
2377 write!(f, " {p}")?;
2378 }
2379 write!(f, ")")?;
2380 }
2381 if self.results().len() > 0 {
2382 write!(f, " (result")?;
2383 for r in self.results() {
2384 write!(f, " {r}")?;
2385 }
2386 write!(f, ")")?;
2387 }
2388 write!(f, "))")
2389 }
2390}
2391
2392impl FuncType {
2393 /// Creates a new function type from the given parameters and results.
2394 ///
2395 /// The function type returned will represent a function which takes
2396 /// `params` as arguments and returns `results` when it is finished.
2397 ///
2398 /// The resulting function type will be final and without a supertype.
2399 ///
2400 /// # Panics
2401 ///
2402 /// Panics if any parameter or value type is not associated with the given
2403 /// engine.
2404 pub fn new(
2405 engine: &Engine,
2406 params: impl IntoIterator<Item = ValType>,
2407 results: impl IntoIterator<Item = ValType>,
2408 ) -> FuncType {
2409 Self::with_finality_and_supertype(engine, Finality::Final, None, params, results)
2410 .expect("cannot fail without a supertype")
2411 }
2412
2413 /// Create a new function type with the given finality, supertype, parameter
2414 /// types, and result types.
2415 ///
2416 /// Returns an error if the supertype is final, or if this function type
2417 /// does not match the supertype.
2418 ///
2419 /// # Panics
2420 ///
2421 /// Panics if any parameter or value type is not associated with the given
2422 /// engine.
2423 pub fn with_finality_and_supertype(
2424 engine: &Engine,
2425 finality: Finality,
2426 supertype: Option<&Self>,
2427 params: impl IntoIterator<Item = ValType>,
2428 results: impl IntoIterator<Item = ValType>,
2429 ) -> Result<Self> {
2430 let params = params.into_iter();
2431 let results = results.into_iter();
2432
2433 let mut wasmtime_params = Vec::with_capacity({
2434 let size_hint = params.size_hint();
2435 let cap = size_hint.1.unwrap_or(size_hint.0);
2436 // Only reserve space if we have a supertype, as that is the only time
2437 // that this vec is used.
2438 supertype.is_some() as usize * cap
2439 });
2440
2441 let mut wasmtime_results = Vec::with_capacity({
2442 let size_hint = results.size_hint();
2443 let cap = size_hint.1.unwrap_or(size_hint.0);
2444 // Same as above.
2445 supertype.is_some() as usize * cap
2446 });
2447
2448 // Keep any of our parameters' and results' `RegisteredType`s alive
2449 // across `Self::from_wasm_func_type`. If one of our given `ValType`s is
2450 // the only thing keeping a type in the registry, we don't want to
2451 // unregister it when we convert the `ValType` into a `WasmValType` just
2452 // before we register our new `WasmFuncType` that will reference it.
2453 let mut registrations = smallvec::SmallVec::<[_; 4]>::new();
2454
2455 let mut to_wasm_type = |ty: ValType, vec: &mut Vec<_>| {
2456 assert!(ty.comes_from_same_engine(engine));
2457
2458 if supertype.is_some() {
2459 vec.push(ty.clone());
2460 }
2461
2462 if let Some(r) = ty.as_ref() {
2463 if let Some(r) = r.heap_type().as_registered_type() {
2464 registrations.push(r.clone());
2465 }
2466 }
2467
2468 ty.to_wasm_type()
2469 };
2470
2471 let wasm_func_ty = WasmFuncType::new(
2472 params
2473 .map(|p| to_wasm_type(p, &mut wasmtime_params))
2474 .collect(),
2475 results
2476 .map(|r| to_wasm_type(r, &mut wasmtime_results))
2477 .collect(),
2478 );
2479
2480 if let Some(supertype) = supertype {
2481 assert!(supertype.comes_from_same_engine(engine));
2482 ensure!(
2483 supertype.finality().is_non_final(),
2484 "cannot create a subtype of a final supertype"
2485 );
2486 ensure!(
2487 Self::matches_impl(
2488 wasmtime_params.iter().cloned(),
2489 supertype.params(),
2490 wasmtime_results.iter().cloned(),
2491 supertype.results()
2492 ),
2493 "function type must match its supertype: found (func{params}{results}), expected \
2494 {supertype}",
2495 params = if wasmtime_params.is_empty() {
2496 String::new()
2497 } else {
2498 let mut s = format!(" (params");
2499 for p in &wasmtime_params {
2500 write!(&mut s, " {p}").unwrap();
2501 }
2502 s.push(')');
2503 s
2504 },
2505 results = if wasmtime_results.is_empty() {
2506 String::new()
2507 } else {
2508 let mut s = format!(" (results");
2509 for r in &wasmtime_results {
2510 write!(&mut s, " {r}").unwrap();
2511 }
2512 s.push(')');
2513 s
2514 },
2515 );
2516 }
2517
2518 Ok(Self::from_wasm_func_type(
2519 engine,
2520 finality.is_final(),
2521 supertype.map(|ty| ty.type_index().into()),
2522 wasm_func_ty,
2523 ))
2524 }
2525
2526 /// Get the engine that this function type is associated with.
2527 pub fn engine(&self) -> &Engine {
2528 self.registered_type.engine()
2529 }
2530
2531 /// Get the finality of this function type.
2532 pub fn finality(&self) -> Finality {
2533 match self.registered_type.is_final {
2534 true => Finality::Final,
2535 false => Finality::NonFinal,
2536 }
2537 }
2538
2539 /// Get the supertype of this function type, if any.
2540 pub fn supertype(&self) -> Option<Self> {
2541 self.registered_type
2542 .supertype
2543 .map(|ty| Self::from_shared_type_index(self.engine(), ty.unwrap_engine_type_index()))
2544 }
2545
2546 /// Get the `i`th parameter type.
2547 ///
2548 /// Returns `None` if `i` is out of bounds.
2549 pub fn param(&self, i: usize) -> Option<ValType> {
2550 let engine = self.engine();
2551 self.registered_type
2552 .unwrap_func()
2553 .params()
2554 .get(i)
2555 .map(|ty| ValType::from_wasm_type(engine, ty))
2556 }
2557
2558 /// Returns the list of parameter types for this function.
2559 #[inline]
2560 pub fn params(&self) -> impl ExactSizeIterator<Item = ValType> + '_ {
2561 let engine = self.engine();
2562 self.registered_type
2563 .unwrap_func()
2564 .params()
2565 .iter()
2566 .map(|ty| ValType::from_wasm_type(engine, ty))
2567 }
2568
2569 /// Get the `i`th result type.
2570 ///
2571 /// Returns `None` if `i` is out of bounds.
2572 pub fn result(&self, i: usize) -> Option<ValType> {
2573 let engine = self.engine();
2574 self.registered_type
2575 .unwrap_func()
2576 .returns()
2577 .get(i)
2578 .map(|ty| ValType::from_wasm_type(engine, ty))
2579 }
2580
2581 /// Returns the list of result types for this function.
2582 #[inline]
2583 pub fn results(&self) -> impl ExactSizeIterator<Item = ValType> + '_ {
2584 let engine = self.engine();
2585 self.registered_type
2586 .unwrap_func()
2587 .returns()
2588 .iter()
2589 .map(|ty| ValType::from_wasm_type(engine, ty))
2590 }
2591
2592 /// Does this function type match the other function type?
2593 ///
2594 /// That is, is this function type a subtype of the other function type?
2595 ///
2596 /// # Panics
2597 ///
2598 /// Panics if either type is associated with a different engine from the
2599 /// other.
2600 pub fn matches(&self, other: &FuncType) -> bool {
2601 assert!(self.comes_from_same_engine(other.engine()));
2602
2603 // Avoid matching on structure for subtyping checks when we have
2604 // precisely the same type.
2605 if self.type_index() == other.type_index() {
2606 return true;
2607 }
2608
2609 Self::matches_impl(
2610 self.params(),
2611 other.params(),
2612 self.results(),
2613 other.results(),
2614 )
2615 }
2616
2617 fn matches_impl(
2618 a_params: impl ExactSizeIterator<Item = ValType>,
2619 b_params: impl ExactSizeIterator<Item = ValType>,
2620 a_results: impl ExactSizeIterator<Item = ValType>,
2621 b_results: impl ExactSizeIterator<Item = ValType>,
2622 ) -> bool {
2623 a_params.len() == b_params.len()
2624 && a_results.len() == b_results.len()
2625 // Params are contravariant and results are covariant. For more
2626 // details and a refresher on variance, read
2627 // https://github.com/bytecodealliance/wasm-tools/blob/f1d89a4/crates/wasmparser/src/readers/core/types/matches.rs#L137-L174
2628 && a_params
2629 .zip(b_params)
2630 .all(|(a, b)| b.matches(&a))
2631 && a_results
2632 .zip(b_results)
2633 .all(|(a, b)| a.matches(&b))
2634 }
2635
2636 /// Is function type `a` precisely equal to function type `b`?
2637 ///
2638 /// Returns `false` even if `a` is a subtype of `b` or vice versa, if they
2639 /// are not exactly the same function type.
2640 ///
2641 /// # Panics
2642 ///
2643 /// Panics if either type is associated with a different engine from the
2644 /// other.
2645 pub fn eq(a: &FuncType, b: &FuncType) -> bool {
2646 assert!(a.comes_from_same_engine(b.engine()));
2647 a.type_index() == b.type_index()
2648 }
2649
2650 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
2651 Engine::same(self.registered_type.engine(), engine)
2652 }
2653
2654 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
2655 self.registered_type.index()
2656 }
2657
2658 pub(crate) fn into_registered_type(self) -> RegisteredType {
2659 self.registered_type
2660 }
2661
2662 /// Construct a `FuncType` from a `WasmFuncType`.
2663 ///
2664 /// This method should only be used when something has already registered --
2665 /// and is *keeping registered* -- any other concrete Wasm types referenced
2666 /// by the given `WasmFuncType`.
2667 ///
2668 /// For example, this method may be called to convert a function type from
2669 /// within a Wasm module's `ModuleTypes` since the Wasm module itself is
2670 /// holding a strong reference to all of its types, including any `(ref null
2671 /// <index>)` types used in the function's parameters and results.
2672 pub(crate) fn from_wasm_func_type(
2673 engine: &Engine,
2674 is_final: bool,
2675 supertype: Option<EngineOrModuleTypeIndex>,
2676 ty: WasmFuncType,
2677 ) -> FuncType {
2678 let ty = RegisteredType::new(
2679 engine,
2680 WasmSubType {
2681 is_final,
2682 supertype,
2683 composite_type: WasmCompositeType {
2684 shared: false,
2685 inner: WasmCompositeInnerType::Func(ty),
2686 },
2687 },
2688 );
2689 Self {
2690 registered_type: ty,
2691 }
2692 }
2693
2694 pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> FuncType {
2695 let ty = RegisteredType::root(engine, index);
2696 Self::from_registered_type(ty)
2697 }
2698
2699 pub(crate) fn from_registered_type(registered_type: RegisteredType) -> Self {
2700 debug_assert!(registered_type.is_func());
2701 Self { registered_type }
2702 }
2703 /// Construct a func which returns results of default value, if each result type has a default value.
2704 pub fn default_value(&self, mut store: impl AsContextMut) -> Result<Func> {
2705 let dummy_results = self
2706 .results()
2707 .map(|ty| ty.default_value())
2708 .collect::<Option<Vec<_>>>()
2709 .ok_or_else(|| anyhow!("function results do not have a default value"))?;
2710 Ok(Func::new(&mut store, self.clone(), move |_, _, results| {
2711 for (slot, dummy) in results.iter_mut().zip(dummy_results.iter()) {
2712 *slot = *dummy;
2713 }
2714 Ok(())
2715 }))
2716 }
2717}
2718
2719// Continuation types
2720/// A WebAssembly continuation descriptor.
2721#[derive(Debug, Clone, Hash)]
2722pub struct ContType {
2723 registered_type: RegisteredType,
2724}
2725
2726impl ContType {
2727 /// Get the engine that this function type is associated with.
2728 pub fn engine(&self) -> &Engine {
2729 self.registered_type.engine()
2730 }
2731
2732 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
2733 Engine::same(self.registered_type.engine(), engine)
2734 }
2735
2736 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
2737 self.registered_type.index()
2738 }
2739
2740 /// Does this continuation type match the other continuation type?
2741 ///
2742 /// That is, is this continuation type a subtype of the other continuation type?
2743 ///
2744 /// # Panics
2745 ///
2746 /// Panics if either type is associated with a different engine from the
2747 /// other.
2748 pub fn matches(&self, other: &ContType) -> bool {
2749 assert!(self.comes_from_same_engine(other.engine()));
2750
2751 // Avoid matching on structure for subtyping checks when we have
2752 // precisely the same type.
2753 // TODO(dhil): Implement subtype check later.
2754 self.type_index() == other.type_index()
2755 }
2756
2757 pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ContType {
2758 let ty = RegisteredType::root(engine, index);
2759 assert!(ty.is_cont());
2760 Self {
2761 registered_type: ty,
2762 }
2763 }
2764}
2765
2766// Exception types
2767
2768/// A WebAssembly exception-object signature type.
2769///
2770/// This type captures the *signature* of an exception object. Note
2771/// that the WebAssembly standard does not define concrete types in
2772/// the heap-type lattice between `exn` (any exception object -- the
2773/// top type) and `noexn` (the uninhabited bottom type). Wasmtime
2774/// defines concrete types based on the *signature* -- that is, the
2775/// function type that describes the signature of the exception
2776/// payload values -- rather than the tag. The tag is a per-instance
2777/// nominal entity (similar to a memory or a table) and is associated
2778/// only with particular exception *objects*.
2779#[derive(Debug, Clone, Hash)]
2780pub struct ExnType {
2781 func_ty: FuncType,
2782 registered_type: RegisteredType,
2783}
2784
2785impl fmt::Display for ExnType {
2786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2787 write!(f, "(exn {}", self.func_ty)?;
2788 for field in self.fields() {
2789 write!(f, " (field {field})")?;
2790 }
2791 write!(f, ")")?;
2792 Ok(())
2793 }
2794}
2795
2796impl ExnType {
2797 /// Create a new `ExnType`.
2798 ///
2799 /// This function creates a new exception object type with the
2800 /// given signature, i.e., list of payload value types. This
2801 /// signature implies a tag type, and when instantiated at
2802 /// runtime, it must be associated with a tag of that type.
2803 pub fn new(engine: &Engine, fields: impl IntoIterator<Item = ValType>) -> Result<ExnType> {
2804 let fields = fields.into_iter().collect::<Vec<_>>();
2805
2806 // First, construct/intern a FuncType: we need this to exist
2807 // so we can hand out a TagType, and it also roots any nested registrations.
2808 let func_ty = FuncType::new(engine, fields.clone(), []);
2809
2810 Ok(Self::_new(engine, fields, func_ty))
2811 }
2812
2813 /// Create a new `ExnType` from an existing `TagType`.
2814 ///
2815 /// This function creates a new exception object type with the
2816 /// signature represented by the tag. The signature must have no
2817 /// result values, i.e., must be of the form `(T1, T2, ...) ->
2818 /// ()`.
2819 pub fn from_tag_type(tag: &TagType) -> Result<ExnType> {
2820 let func_ty = tag.ty();
2821
2822 // Check that the tag's signature type has no results.
2823 ensure!(
2824 func_ty.results().len() == 0,
2825 "Cannot create an exception type from a tag type with results in the signature"
2826 );
2827
2828 Ok(Self::_new(
2829 tag.ty.engine(),
2830 func_ty.params(),
2831 func_ty.clone(),
2832 ))
2833 }
2834
2835 fn _new(
2836 engine: &Engine,
2837 fields: impl IntoIterator<Item = ValType>,
2838 func_ty: FuncType,
2839 ) -> ExnType {
2840 let fields = fields
2841 .into_iter()
2842 .map(|ty| {
2843 assert!(ty.comes_from_same_engine(engine));
2844 WasmFieldType {
2845 element_type: WasmStorageType::Val(ty.to_wasm_type()),
2846 mutable: false,
2847 }
2848 })
2849 .collect();
2850
2851 let ty = RegisteredType::new(
2852 engine,
2853 WasmSubType {
2854 is_final: true,
2855 supertype: None,
2856 composite_type: WasmCompositeType {
2857 shared: false,
2858 inner: WasmCompositeInnerType::Exn(WasmExnType {
2859 func_ty: EngineOrModuleTypeIndex::Engine(func_ty.type_index()),
2860 fields,
2861 }),
2862 },
2863 },
2864 );
2865
2866 Self {
2867 func_ty,
2868 registered_type: ty,
2869 }
2870 }
2871
2872 /// Get the tag type that this exception type is associated with.
2873 pub fn tag_type(&self) -> TagType {
2874 TagType {
2875 ty: self.func_ty.clone(),
2876 }
2877 }
2878
2879 /// Get the `i`th field type.
2880 ///
2881 /// Returns `None` if `i` is out of bounds.
2882 pub fn field(&self, i: usize) -> Option<FieldType> {
2883 let engine = self.engine();
2884 self.as_wasm_exn_type()
2885 .fields
2886 .get(i)
2887 .map(|ty| FieldType::from_wasm_field_type(engine, ty))
2888 }
2889
2890 /// Returns the list of field types for this function.
2891 #[inline]
2892 pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldType> + '_ {
2893 let engine = self.engine();
2894 self.as_wasm_exn_type()
2895 .fields
2896 .iter()
2897 .map(|ty| FieldType::from_wasm_field_type(engine, ty))
2898 }
2899
2900 /// Get the engine that this exception type is associated with.
2901 pub fn engine(&self) -> &Engine {
2902 self.registered_type.engine()
2903 }
2904
2905 pub(crate) fn comes_from_same_engine(&self, engine: &Engine) -> bool {
2906 Engine::same(self.registered_type.engine(), engine)
2907 }
2908
2909 pub(crate) fn as_wasm_exn_type(&self) -> &WasmExnType {
2910 self.registered_type().unwrap_exn()
2911 }
2912
2913 pub(crate) fn type_index(&self) -> VMSharedTypeIndex {
2914 self.registered_type.index()
2915 }
2916
2917 /// Does this exception type match the other exception type?
2918 ///
2919 /// That is, is this exception type a subtype of the other exception type?
2920 ///
2921 /// # Panics
2922 ///
2923 /// Panics if either type is associated with a different engine from the
2924 /// other.
2925 pub fn matches(&self, other: &ExnType) -> bool {
2926 assert!(self.comes_from_same_engine(other.engine()));
2927
2928 // We have no concrete-exception-type subtyping; concrete
2929 // exception types are only (mutually, trivially) subtypes if
2930 // they are exactly equal.
2931 self.type_index() == other.type_index()
2932 }
2933
2934 pub(crate) fn registered_type(&self) -> &RegisteredType {
2935 &self.registered_type
2936 }
2937
2938 pub(crate) fn from_shared_type_index(engine: &Engine, index: VMSharedTypeIndex) -> ExnType {
2939 let ty = RegisteredType::root(engine, index);
2940 assert!(ty.is_exn());
2941 let func_ty = FuncType::from_shared_type_index(
2942 engine,
2943 ty.unwrap_exn().func_ty.unwrap_engine_type_index(),
2944 );
2945 Self {
2946 func_ty,
2947 registered_type: ty,
2948 }
2949 }
2950}
2951
2952// Global Types
2953
2954/// A WebAssembly global descriptor.
2955///
2956/// This type describes an instance of a global in a WebAssembly module. Globals
2957/// are local to an [`Instance`](crate::Instance) and are either immutable or
2958/// mutable.
2959#[derive(Debug, Clone, Hash)]
2960pub struct GlobalType {
2961 content: ValType,
2962 mutability: Mutability,
2963}
2964
2965impl GlobalType {
2966 /// Creates a new global descriptor of the specified `content` type and
2967 /// whether or not it's mutable.
2968 pub fn new(content: ValType, mutability: Mutability) -> GlobalType {
2969 GlobalType {
2970 content,
2971 mutability,
2972 }
2973 }
2974
2975 /// Returns the value type of this global descriptor.
2976 pub fn content(&self) -> &ValType {
2977 &self.content
2978 }
2979
2980 /// Returns whether or not this global is mutable.
2981 pub fn mutability(&self) -> Mutability {
2982 self.mutability
2983 }
2984
2985 /// Returns `None` if the wasmtime global has a type that we can't
2986 /// represent, but that should only very rarely happen and indicate a bug.
2987 pub(crate) fn from_wasmtime_global(engine: &Engine, global: &Global) -> GlobalType {
2988 let ty = ValType::from_wasm_type(engine, &global.wasm_ty);
2989 let mutability = if global.mutability {
2990 Mutability::Var
2991 } else {
2992 Mutability::Const
2993 };
2994 GlobalType::new(ty, mutability)
2995 }
2996 /// Construct a new global import with this type’s default value.
2997 ///
2998 /// This creates a host `Global` in the given store initialized to the
2999 /// type’s zero/null default (e.g. `0` for numeric globals, `null_ref` for refs).
3000 pub fn default_value(&self, store: impl AsContextMut) -> Result<RuntimeGlobal> {
3001 let val = self
3002 .content()
3003 .default_value()
3004 .ok_or_else(|| anyhow!("global type has no default value"))?;
3005 RuntimeGlobal::new(store, self.clone(), val)
3006 }
3007
3008 pub(crate) fn into_registered_type(self) -> Option<RegisteredType> {
3009 self.content.into_registered_type()
3010 }
3011}
3012
3013// Tag Types
3014
3015/// A descriptor for a tag in a WebAssembly module.
3016///
3017/// Note that tags are local to an [`Instance`](crate::Instance),
3018/// i.e., are a runtime entity. However, a tag is associated with a
3019/// function type, and so has a kind of static type. This descriptor
3020/// is a thin wrapper around a `FuncType` representing the function
3021/// type of a tag.
3022#[derive(Debug, Clone, Hash)]
3023pub struct TagType {
3024 ty: FuncType,
3025}
3026
3027impl TagType {
3028 /// Creates a new global descriptor of the specified type.
3029 pub fn new(ty: FuncType) -> TagType {
3030 TagType { ty }
3031 }
3032
3033 /// Returns the underlying function type of this tag descriptor.
3034 pub fn ty(&self) -> &FuncType {
3035 &self.ty
3036 }
3037
3038 pub(crate) fn from_wasmtime_tag(engine: &Engine, tag: &Tag) -> TagType {
3039 let ty = FuncType::from_shared_type_index(engine, tag.signature.unwrap_engine_type_index());
3040 TagType { ty }
3041 }
3042
3043 /// Construct a new default tag with this type.
3044 ///
3045 /// This creates a host `Tag` in the given store. Tag instances
3046 /// have no content other than their type, so this "default" value
3047 /// is identical to ordinary host tag allocation.
3048 pub fn default_value(&self, store: impl AsContextMut) -> Result<RuntimeTag> {
3049 RuntimeTag::new(store, self)
3050 }
3051}
3052
3053// Table Types
3054
3055/// A descriptor for a table in a WebAssembly module.
3056///
3057/// Tables are contiguous chunks of a specific element, typically a `funcref` or
3058/// an `externref`. The most common use for tables is a function table through
3059/// which `call_indirect` can invoke other functions.
3060#[derive(Debug, Clone, Hash)]
3061pub struct TableType {
3062 // Keep a `wasmtime::RefType` so that `TableType::element` doesn't need to
3063 // take an `&Engine`.
3064 element: RefType,
3065 ty: Table,
3066}
3067
3068impl TableType {
3069 /// Creates a new table descriptor which will contain the specified
3070 /// `element` and have the `limits` applied to its length.
3071 pub fn new(element: RefType, min: u32, max: Option<u32>) -> TableType {
3072 let ref_type = element.to_wasm_type();
3073
3074 debug_assert!(
3075 ref_type.is_canonicalized_for_runtime_usage(),
3076 "should be canonicalized for runtime usage: {ref_type:?}"
3077 );
3078
3079 let limits = Limits {
3080 min: u64::from(min),
3081 max: max.map(|x| u64::from(x)),
3082 };
3083
3084 TableType {
3085 element,
3086 ty: Table {
3087 idx_type: IndexType::I32,
3088 limits,
3089 ref_type,
3090 },
3091 }
3092 }
3093
3094 /// Crates a new descriptor for a 64-bit table.
3095 ///
3096 /// Note that 64-bit tables are part of the memory64 proposal for
3097 /// WebAssembly which is not standardized yet.
3098 pub fn new64(element: RefType, min: u64, max: Option<u64>) -> TableType {
3099 let ref_type = element.to_wasm_type();
3100
3101 debug_assert!(
3102 ref_type.is_canonicalized_for_runtime_usage(),
3103 "should be canonicalized for runtime usage: {ref_type:?}"
3104 );
3105
3106 TableType {
3107 element,
3108 ty: Table {
3109 ref_type,
3110 idx_type: IndexType::I64,
3111 limits: Limits { min, max },
3112 },
3113 }
3114 }
3115
3116 /// Returns whether or not this table is a 64-bit table.
3117 ///
3118 /// Note that 64-bit tables are part of the memory64 proposal for
3119 /// WebAssembly which is not standardized yet.
3120 pub fn is_64(&self) -> bool {
3121 matches!(self.ty.idx_type, IndexType::I64)
3122 }
3123
3124 /// Returns the element value type of this table.
3125 pub fn element(&self) -> &RefType {
3126 &self.element
3127 }
3128
3129 /// Returns minimum number of elements this table must have
3130 pub fn minimum(&self) -> u64 {
3131 self.ty.limits.min
3132 }
3133
3134 /// Returns the optionally-specified maximum number of elements this table
3135 /// can have.
3136 ///
3137 /// If this returns `None` then the table is not limited in size.
3138 pub fn maximum(&self) -> Option<u64> {
3139 self.ty.limits.max
3140 }
3141
3142 pub(crate) fn from_wasmtime_table(engine: &Engine, table: &Table) -> TableType {
3143 let element = RefType::from_wasm_type(engine, &table.ref_type);
3144 TableType {
3145 element,
3146 ty: *table,
3147 }
3148 }
3149
3150 pub(crate) fn wasmtime_table(&self) -> &Table {
3151 &self.ty
3152 }
3153 /// Construct a new table import whose entries are filled with this type’s default.
3154 ///
3155 /// Creates a host `Table` in the store with its initial size and element
3156 /// type’s default (e.g. `null_ref` for nullable refs).
3157 pub fn default_value(&self, store: impl AsContextMut) -> Result<RuntimeTable> {
3158 let val: ValType = self.element().clone().into();
3159 let init_val = val
3160 .default_value()
3161 .context("table element type does not have a default value")?
3162 .ref_()
3163 .unwrap();
3164 RuntimeTable::new(store, self.clone(), init_val)
3165 }
3166}
3167
3168// Memory Types
3169
3170/// A builder for [`MemoryType`][crate::MemoryType]s.
3171///
3172/// A new builder can be constructed via its `Default` implementation.
3173///
3174/// When you're done configuring, get the underlying
3175/// [`MemoryType`][crate::MemoryType] by calling the
3176/// [`build`][crate::MemoryTypeBuilder::build] method.
3177///
3178/// # Example
3179///
3180/// ```
3181/// # fn foo() -> wasmtime::Result<()> {
3182/// use wasmtime::MemoryTypeBuilder;
3183///
3184/// let memory_type = MemoryTypeBuilder::new()
3185/// // Set the minimum size, in pages.
3186/// .min(4096)
3187/// // Set the maximum size, in pages.
3188/// .max(Some(4096))
3189/// // Set the page size to 1 byte (aka 2**0).
3190/// .page_size_log2(0)
3191/// // Get the underlying memory type.
3192/// .build()?;
3193/// # Ok(())
3194/// # }
3195/// ```
3196pub struct MemoryTypeBuilder {
3197 ty: Memory,
3198}
3199
3200impl Default for MemoryTypeBuilder {
3201 fn default() -> Self {
3202 MemoryTypeBuilder {
3203 ty: Memory {
3204 idx_type: IndexType::I32,
3205 limits: Limits { min: 0, max: None },
3206 shared: false,
3207 page_size_log2: Memory::DEFAULT_PAGE_SIZE_LOG2,
3208 },
3209 }
3210 }
3211}
3212
3213impl MemoryTypeBuilder {
3214 /// Create a new builder for a [`MemoryType`] with the default settings.
3215 ///
3216 /// By default memory types have the following properties:
3217 ///
3218 /// * The minimum memory size is 0 pages.
3219 /// * The maximum memory size is unspecified.
3220 /// * Memories use 32-bit indexes.
3221 /// * The page size is 64KiB.
3222 ///
3223 /// Each option can be configured through the methods on the returned
3224 /// builder.
3225 pub fn new() -> MemoryTypeBuilder {
3226 MemoryTypeBuilder::default()
3227 }
3228
3229 fn validate(&self) -> Result<()> {
3230 if self
3231 .ty
3232 .limits
3233 .max
3234 .map_or(false, |max| max < self.ty.limits.min)
3235 {
3236 bail!("maximum page size cannot be smaller than the minimum page size");
3237 }
3238
3239 match self.ty.page_size_log2 {
3240 0 | Memory::DEFAULT_PAGE_SIZE_LOG2 => {}
3241 x => bail!(
3242 "page size must be 2**16 or 2**0, but was given 2**{x}; note \
3243 that future Wasm extensions might allow any power of two page \
3244 size, but only 2**16 and 2**0 are currently valid",
3245 ),
3246 }
3247
3248 if self.ty.shared && self.ty.limits.max.is_none() {
3249 bail!("shared memories must have a maximum size");
3250 }
3251
3252 let absolute_max = self.ty.max_size_based_on_index_type();
3253 let min = self
3254 .ty
3255 .minimum_byte_size()
3256 .context("memory's minimum byte size must fit in a u64")?;
3257 if min > absolute_max {
3258 bail!("minimum size is too large for this memory type's index type");
3259 }
3260 if self
3261 .ty
3262 .maximum_byte_size()
3263 .map_or(false, |max| max > absolute_max)
3264 {
3265 bail!("maximum size is too large for this memory type's index type");
3266 }
3267
3268 Ok(())
3269 }
3270
3271 /// Set the minimum size, in units of pages, for the memory type being
3272 /// built.
3273 ///
3274 /// The default minimum is `0`.
3275 pub fn min(&mut self, minimum: u64) -> &mut Self {
3276 self.ty.limits.min = minimum;
3277 self
3278 }
3279
3280 /// Set the maximum size, in units of pages, for the memory type being
3281 /// built.
3282 ///
3283 /// The default maximum is `None`.
3284 pub fn max(&mut self, maximum: Option<u64>) -> &mut Self {
3285 self.ty.limits.max = maximum;
3286 self
3287 }
3288
3289 /// Set whether this is a 64-bit memory or not.
3290 ///
3291 /// If a memory is not a 64-bit memory, then it is a 32-bit memory.
3292 ///
3293 /// The default is `false`, aka 32-bit memories.
3294 ///
3295 /// Note that 64-bit memories are part of [the memory64
3296 /// proposal](https://github.com/WebAssembly/memory64) for WebAssembly which
3297 /// is not fully standardized yet.
3298 pub fn memory64(&mut self, memory64: bool) -> &mut Self {
3299 self.ty.idx_type = match memory64 {
3300 true => IndexType::I64,
3301 false => IndexType::I32,
3302 };
3303 self
3304 }
3305
3306 /// Set the sharedness for the memory type being built.
3307 ///
3308 /// The default is `false`, aka unshared.
3309 ///
3310 /// Note that shared memories are part of [the threads
3311 /// proposal](https://github.com/WebAssembly/threads) for WebAssembly which
3312 /// is not fully standardized yet.
3313 pub fn shared(&mut self, shared: bool) -> &mut Self {
3314 self.ty.shared = shared;
3315 self
3316 }
3317
3318 /// Set the log base 2 of the page size, in bytes, for the memory type being
3319 /// built.
3320 ///
3321 /// The default value is `16`, which results in the default Wasm page size
3322 /// of 64KiB (aka 2<sup>16</sup> or 65536).
3323 ///
3324 /// Other than `16`, the only valid value is `0`, which results in a page
3325 /// size of one byte (aka 2<sup>0</sup>). Single-byte page sizes can be used
3326 /// to get fine-grained control over a Wasm memory's resource consumption
3327 /// and run Wasm in embedded environments with less than 64KiB of RAM, for
3328 /// example.
3329 ///
3330 /// Future extensions to the core WebAssembly language might relax these
3331 /// constraints and introduce more valid page sizes, such as any power of
3332 /// two between 1 and 65536 inclusive.
3333 ///
3334 /// Note that non-default page sizes are part of [the custom-page-sizes
3335 /// proposal](https://github.com/WebAssembly/custom-page-sizes) for
3336 /// WebAssembly which is not fully standardized yet.
3337 pub fn page_size_log2(&mut self, page_size_log2: u8) -> &mut Self {
3338 self.ty.page_size_log2 = page_size_log2;
3339 self
3340 }
3341
3342 /// Get the underlying memory type that this builder has been building.
3343 ///
3344 /// # Errors
3345 ///
3346 /// Returns an error if the configured memory type is invalid, for example
3347 /// if the maximum size is smaller than the minimum size.
3348 pub fn build(&self) -> Result<MemoryType> {
3349 self.validate()?;
3350 Ok(MemoryType { ty: self.ty })
3351 }
3352}
3353
3354/// A descriptor for a WebAssembly memory type.
3355///
3356/// Memories are described in units of pages (64KB) and represent contiguous
3357/// chunks of addressable memory.
3358#[derive(Debug, Clone, Hash, Eq, PartialEq)]
3359pub struct MemoryType {
3360 ty: Memory,
3361}
3362
3363impl MemoryType {
3364 /// Creates a new descriptor for a 32-bit WebAssembly memory given the
3365 /// specified limits of the memory.
3366 ///
3367 /// The `minimum` and `maximum` values here are specified in units of
3368 /// WebAssembly pages, which are 64KiB by default. Use
3369 /// [`MemoryTypeBuilder`][crate::MemoryTypeBuilder] if you want a
3370 /// non-default page size.
3371 ///
3372 /// # Panics
3373 ///
3374 /// Panics if the minimum is greater than the maximum or if the minimum or
3375 /// maximum number of pages can result in a byte size that is not
3376 /// addressable with a 32-bit integer.
3377 pub fn new(minimum: u32, maximum: Option<u32>) -> MemoryType {
3378 MemoryTypeBuilder::default()
3379 .min(minimum.into())
3380 .max(maximum.map(Into::into))
3381 .build()
3382 .unwrap()
3383 }
3384
3385 /// Creates a new descriptor for a 64-bit WebAssembly memory given the
3386 /// specified limits of the memory.
3387 ///
3388 /// The `minimum` and `maximum` values here are specified in units of
3389 /// WebAssembly pages, which are 64KiB by default. Use
3390 /// [`MemoryTypeBuilder`][crate::MemoryTypeBuilder] if you want a
3391 /// non-default page size.
3392 ///
3393 /// Note that 64-bit memories are part of [the memory64
3394 /// proposal](https://github.com/WebAssembly/memory64) for WebAssembly which
3395 /// is not fully standardized yet.
3396 ///
3397 /// # Panics
3398 ///
3399 /// Panics if the minimum is greater than the maximum or if the minimum or
3400 /// maximum number of pages can result in a byte size that is not
3401 /// addressable with a 64-bit integer.
3402 pub fn new64(minimum: u64, maximum: Option<u64>) -> MemoryType {
3403 MemoryTypeBuilder::default()
3404 .memory64(true)
3405 .min(minimum)
3406 .max(maximum)
3407 .build()
3408 .unwrap()
3409 }
3410
3411 /// Creates a new descriptor for shared WebAssembly memory given the
3412 /// specified limits of the memory.
3413 ///
3414 /// The `minimum` and `maximum` values here are specified in units of
3415 /// WebAssembly pages, which are 64KiB by default. Use
3416 /// [`MemoryTypeBuilder`][crate::MemoryTypeBuilder] if you want a
3417 /// non-default page size.
3418 ///
3419 /// Note that shared memories are part of [the threads
3420 /// proposal](https://github.com/WebAssembly/threads) for WebAssembly which
3421 /// is not fully standardized yet.
3422 ///
3423 /// # Panics
3424 ///
3425 /// Panics if the minimum is greater than the maximum or if the minimum or
3426 /// maximum number of pages can result in a byte size that is not
3427 /// addressable with a 32-bit integer.
3428 pub fn shared(minimum: u32, maximum: u32) -> MemoryType {
3429 MemoryTypeBuilder::default()
3430 .shared(true)
3431 .min(minimum.into())
3432 .max(Some(maximum.into()))
3433 .build()
3434 .unwrap()
3435 }
3436
3437 /// Creates a new [`MemoryTypeBuilder`] to configure all the various knobs
3438 /// of the final memory type being created.
3439 ///
3440 /// This is a convenience function for [`MemoryTypeBuilder::new`].
3441 pub fn builder() -> MemoryTypeBuilder {
3442 MemoryTypeBuilder::new()
3443 }
3444
3445 /// Returns whether this is a 64-bit memory or not.
3446 ///
3447 /// Note that 64-bit memories are part of the memory64 proposal for
3448 /// WebAssembly which is not standardized yet.
3449 pub fn is_64(&self) -> bool {
3450 matches!(self.ty.idx_type, IndexType::I64)
3451 }
3452
3453 /// Returns whether this is a shared memory or not.
3454 ///
3455 /// Note that shared memories are part of the threads proposal for
3456 /// WebAssembly which is not standardized yet.
3457 pub fn is_shared(&self) -> bool {
3458 self.ty.shared
3459 }
3460
3461 /// Returns minimum number of WebAssembly pages this memory must have.
3462 ///
3463 /// Note that the return value, while a `u64`, will always fit into a `u32`
3464 /// for 32-bit memories.
3465 pub fn minimum(&self) -> u64 {
3466 self.ty.limits.min
3467 }
3468
3469 /// Returns the optionally-specified maximum number of pages this memory
3470 /// can have.
3471 ///
3472 /// If this returns `None` then the memory is not limited in size.
3473 ///
3474 /// Note that the return value, while a `u64`, will always fit into a `u32`
3475 /// for 32-bit memories.
3476 pub fn maximum(&self) -> Option<u64> {
3477 self.ty.limits.max
3478 }
3479
3480 /// This memory's page size, in bytes.
3481 pub fn page_size(&self) -> u64 {
3482 self.ty.page_size()
3483 }
3484
3485 /// The log2 of this memory's page size, in bytes.
3486 pub fn page_size_log2(&self) -> u8 {
3487 self.ty.page_size_log2
3488 }
3489
3490 pub(crate) fn from_wasmtime_memory(memory: &Memory) -> MemoryType {
3491 MemoryType { ty: *memory }
3492 }
3493
3494 pub(crate) fn wasmtime_memory(&self) -> &Memory {
3495 &self.ty
3496 }
3497 /// Construct a new memory import initialized to this memory type’s default state
3498 ///
3499 /// Returns a host `Memory` in the given store with the configured initial
3500 /// page size and zeroed contents.
3501 pub fn default_value(&self, store: impl AsContextMut) -> Result<RuntimeMemory> {
3502 RuntimeMemory::new(store, self.clone())
3503 }
3504}
3505
3506// Import Types
3507
3508/// A descriptor for an imported value into a wasm module.
3509///
3510/// This type is primarily accessed from the
3511/// [`Module::imports`](crate::Module::imports) API. Each [`ImportType`]
3512/// describes an import into the wasm module with the module/name that it's
3513/// imported from as well as the type of item that's being imported.
3514#[derive(Clone)]
3515pub struct ImportType<'module> {
3516 /// The module of the import.
3517 module: &'module str,
3518
3519 /// The field of the import.
3520 name: &'module str,
3521
3522 /// The type of the import.
3523 ty: EntityType,
3524 types: &'module ModuleTypes,
3525 engine: &'module Engine,
3526}
3527
3528impl<'module> ImportType<'module> {
3529 /// Creates a new import descriptor which comes from `module` and `name` and
3530 /// is of type `ty`.
3531 pub(crate) fn new(
3532 module: &'module str,
3533 name: &'module str,
3534 ty: EntityType,
3535 types: &'module ModuleTypes,
3536 engine: &'module Engine,
3537 ) -> ImportType<'module> {
3538 assert!(ty.is_canonicalized_for_runtime_usage());
3539 ImportType {
3540 module,
3541 name,
3542 ty,
3543 types,
3544 engine,
3545 }
3546 }
3547
3548 /// Returns the module name that this import is expected to come from.
3549 pub fn module(&self) -> &'module str {
3550 self.module
3551 }
3552
3553 /// Returns the field name of the module that this import is expected to
3554 /// come from.
3555 pub fn name(&self) -> &'module str {
3556 self.name
3557 }
3558
3559 /// Returns the expected type of this import.
3560 pub fn ty(&self) -> ExternType {
3561 ExternType::from_wasmtime(self.engine, self.types, &self.ty)
3562 }
3563}
3564
3565impl<'module> fmt::Debug for ImportType<'module> {
3566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3567 f.debug_struct("ImportType")
3568 .field("module", &self.module())
3569 .field("name", &self.name())
3570 .field("ty", &self.ty())
3571 .finish()
3572 }
3573}
3574
3575// Export Types
3576
3577/// A descriptor for an exported WebAssembly value.
3578///
3579/// This type is primarily accessed from the
3580/// [`Module::exports`](crate::Module::exports) accessor and describes what
3581/// names are exported from a wasm module and the type of the item that is
3582/// exported.
3583#[derive(Clone)]
3584pub struct ExportType<'module> {
3585 /// The name of the export.
3586 name: &'module str,
3587
3588 /// The type of the export.
3589 ty: EntityType,
3590 types: &'module ModuleTypes,
3591 engine: &'module Engine,
3592}
3593
3594impl<'module> ExportType<'module> {
3595 /// Creates a new export which is exported with the given `name` and has the
3596 /// given `ty`.
3597 pub(crate) fn new(
3598 name: &'module str,
3599 ty: EntityType,
3600 types: &'module ModuleTypes,
3601 engine: &'module Engine,
3602 ) -> ExportType<'module> {
3603 ExportType {
3604 name,
3605 ty,
3606 types,
3607 engine,
3608 }
3609 }
3610
3611 /// Returns the name by which this export is known.
3612 pub fn name(&self) -> &'module str {
3613 self.name
3614 }
3615
3616 /// Returns the type of this export.
3617 pub fn ty(&self) -> ExternType {
3618 ExternType::from_wasmtime(self.engine, self.types, &self.ty)
3619 }
3620}
3621
3622impl<'module> fmt::Debug for ExportType<'module> {
3623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3624 f.debug_struct("ExportType")
3625 .field("name", &self.name().to_owned())
3626 .field("ty", &self.ty())
3627 .finish()
3628 }
3629}