use alloc::string::{String, ToString};1use core::fmt;2use core::num::TryFromIntError;34/// A WebAssembly translation error.5///6/// When a WebAssembly function can't be translated, one of these error codes will be returned7/// to describe the failure.8#[derive(Debug)]9pub enum WasmError {10/// The input WebAssembly code is invalid.11///12/// This error code is used by a WebAssembly translator when it encounters invalid WebAssembly13/// code. This should never happen for validated WebAssembly code.14InvalidWebAssembly {15/// A string describing the validation error.16message: String,17/// The bytecode offset where the error occurred.18offset: usize,19},2021/// A feature used by the WebAssembly code is not supported by the embedding environment.22///23/// Embedding environments may have their own limitations and feature restrictions.24Unsupported(String),2526/// An implementation limit was exceeded.27///28/// Cranelift can compile very large and complicated functions, but the [implementation has29/// limits][limits] that cause compilation to fail when they are exceeded.30///31/// [limits]: https://github.com/bytecodealliance/wasmtime/blob/main/cranelift/docs/ir.md#implementation-limits32ImplLimitExceeded,3334/// Any user-defined error.35User(String),36}3738/// Return an `Err(WasmError::Unsupported(msg))` where `msg` the string built by calling `format!`39/// on the arguments to this macro.40#[macro_export]41macro_rules! wasm_unsupported {42($($arg:tt)*) => { $crate::WasmError::Unsupported($crate::__format!($($arg)*)) }43}44#[doc(hidden)]45pub use alloc::format as __format;4647impl From<wasmparser::BinaryReaderError> for WasmError {48/// Convert from a `BinaryReaderError` to a `WasmError`.49fn from(e: wasmparser::BinaryReaderError) -> Self {50Self::InvalidWebAssembly {51message: e.message().into(),52offset: e.offset(),53}54}55}5657impl From<TryFromIntError> for WasmError {58/// Convert from a `TryFromIntError` to a `WasmError`.59fn from(e: TryFromIntError) -> Self {60Self::InvalidWebAssembly {61message: e.to_string(),62offset: 0,63}64}65}6667/// A convenient alias for a `Result` that uses `WasmError` as the error type.68pub type WasmResult<T> = Result<T, WasmError>;6970impl fmt::Display for WasmError {71fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {72match self {73WasmError::InvalidWebAssembly { message, offset } => {74write!(75f,76"Invalid input WebAssembly code at offset {offset}: {message}"77)78}79WasmError::Unsupported(s) => {80write!(f, "Unsupported feature: {s}")81}82WasmError::ImplLimitExceeded => {83write!(f, "Implementation limit exceeded")84}85WasmError::User(s) => {86write!(f, "User error: {s}")87}88}89}90}9192impl core::error::Error for WasmError {}939495