wasm_wave/wasm/
mod.rs

1//! Wasm type and value types
2
3mod fmt;
4mod func;
5mod ty;
6mod val;
7
8use alloc::string::{String, ToString};
9pub use fmt::{DisplayFunc, DisplayFuncArgs, DisplayFuncResults, DisplayType, DisplayValue};
10pub use func::WasmFunc;
11pub use ty::{WasmType, WasmTypeKind};
12pub use val::WasmValue;
13
14pub(crate) use ty::maybe_unwrap_type;
15pub(crate) use val::unwrap_val;
16
17/// Returns an error if the given [`WasmType`] is not of the given [`WasmTypeKind`].
18pub fn ensure_type_kind(ty: &impl WasmType, kind: WasmTypeKind) -> Result<(), WasmValueError> {
19    if ty.kind() == kind {
20        Ok(())
21    } else {
22        Err(WasmValueError::WrongTypeKind {
23            ty: DisplayType(ty).to_string(),
24            kind,
25        })
26    }
27}
28
29/// An error from creating a [`WasmValue`].
30#[derive(Debug)]
31#[allow(missing_docs)]
32pub enum WasmValueError {
33    MissingField(String),
34    MissingPayload(String),
35    UnexpectedPayload(String),
36    UnknownCase(String),
37    UnknownField(String),
38    UnsupportedType(String),
39    WrongNumberOfTupleValues { want: usize, got: usize },
40    WrongTypeKind { kind: WasmTypeKind, ty: String },
41    WrongValueType { ty: String, val: String },
42    Other(String),
43}
44
45impl WasmValueError {
46    pub(crate) fn wrong_value_type(ty: &impl WasmType, val: &impl WasmValue) -> Self {
47        Self::WrongValueType {
48            ty: DisplayType(ty).to_string(),
49            val: DisplayValue(val).to_string(),
50        }
51    }
52}
53
54impl core::fmt::Display for WasmValueError {
55    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
56        match self {
57            Self::MissingField(name) => {
58                write!(f, "missing field {name:?}")
59            }
60            Self::MissingPayload(name) => write!(f, "missing payload for {name:?} case"),
61            Self::UnexpectedPayload(name) => write!(f, "unexpected payload for {name:?} case"),
62            Self::UnknownCase(name) => write!(f, "unknown case {name:?}"),
63            Self::UnknownField(name) => write!(f, "unknown field {name:?}"),
64            Self::UnsupportedType(ty) => write!(f, "unsupported type {ty}"),
65            Self::WrongNumberOfTupleValues { want, got } => {
66                write!(f, "expected {want} tuple elements; got {got}")
67            }
68            Self::WrongTypeKind { kind, ty } => {
69                write!(f, "expected a {kind}; got {ty}")
70            }
71            Self::WrongValueType { ty, val } => {
72                write!(f, "expected a {ty}; got {val}")
73            }
74            Self::Other(msg) => write!(f, "{msg}"),
75        }
76    }
77}
78
79impl core::error::Error for WasmValueError {}