wasmtime_types/error.rs
1use alloc::string::String;
2use core::fmt;
3
4/// A WebAssembly translation error.
5///
6/// When a WebAssembly function can't be translated, one of these error codes will be returned
7/// 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 WebAssembly
13 /// code. This should never happen for validated WebAssembly code.
14 InvalidWebAssembly {
15 /// A string describing the validation error.
16 message: String,
17 /// The bytecode offset where the error occurred.
18 offset: usize,
19 },
20
21 /// 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.
24 Unsupported(String),
25
26 /// An implementation limit was exceeded.
27 ///
28 /// Cranelift can compile very large and complicated functions, but the [implementation has
29 /// 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-limits
32 ImplLimitExceeded,
33
34 /// Any user-defined error.
35 User(String),
36}
37
38/// 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
45impl From<wasmparser::BinaryReaderError> for WasmError {
46 /// Convert from a `BinaryReaderError` to a `WasmError`.
47 fn from(e: wasmparser::BinaryReaderError) -> Self {
48 Self::InvalidWebAssembly {
49 message: e.message().into(),
50 offset: e.offset(),
51 }
52 }
53}
54
55/// A convenient alias for a `Result` that uses `WasmError` as the error type.
56pub type WasmResult<T> = Result<T, WasmError>;
57
58impl fmt::Display for WasmError {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 match self {
61 WasmError::InvalidWebAssembly { message, offset } => {
62 write!(
63 f,
64 "Invalid input WebAssembly code at offset {offset}: {message}"
65 )
66 }
67 WasmError::Unsupported(s) => {
68 write!(f, "Unsupported feature: {s}")
69 }
70 WasmError::ImplLimitExceeded => {
71 write!(f, "Implementation limit exceeded")
72 }
73 WasmError::User(s) => {
74 write!(f, "User error: {s}")
75 }
76 }
77 }
78}
79
80#[cfg(feature = "std")]
81impl std::error::Error for WasmError {}