midenc_frontend_wasm/
error.rs

1use midenc_session::diagnostics::{miette, Diagnostic, Report};
2use thiserror::Error;
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#[allow(missing_docs)]
9#[derive(Error, Debug, Diagnostic)]
10pub enum WasmError {
11    /// The input WebAssembly code is invalid.
12    ///
13    /// This error code is used by a WebAssembly translator when it encounters invalid WebAssembly
14    /// code. This should never happen for validated WebAssembly code.
15    #[error("invalid input WebAssembly code at offset {offset}: {message}")]
16    #[diagnostic()]
17    InvalidWebAssembly {
18        /// A string describing the validation error.
19        message: String,
20        /// The bytecode offset where the error occurred.
21        offset: usize,
22    },
23
24    /// A feature used by the WebAssembly code is not supported by the Miden IR.
25    #[error("unsupported WebAssembly code: {0}")]
26    #[diagnostic()]
27    Unsupported(String),
28
29    /// Too many functions were declared in a module
30    #[error("Too many declared functions in the module")]
31    #[diagnostic()]
32    FuncNumLimitExceeded,
33
34    #[error("import metadata is missing: {0}")]
35    #[diagnostic()]
36    MissingImportMetadata(String),
37
38    #[error("export metadata is missing: {0}")]
39    #[diagnostic()]
40    MissingExportMetadata(String),
41
42    #[error(transparent)]
43    DwarfError(#[from] gimli::Error),
44
45    #[error(transparent)]
46    Io(#[from] std::io::Error),
47}
48
49impl From<wasmparser::BinaryReaderError> for WasmError {
50    fn from(e: wasmparser::BinaryReaderError) -> Self {
51        Self::InvalidWebAssembly {
52            message: e.message().into(),
53            offset: e.offset(),
54        }
55    }
56}
57
58/// A convenient alias for a `Result` that uses `WasmError` as the error type.
59pub type WasmResult<T> = Result<T, Report>;
60
61/// Emit diagnostics and return an `Err(WasmError::Unsupported(msg))` where `msg` the string built
62/// by calling `format!` on the arguments to this macro.
63#[macro_export]
64macro_rules! unsupported_diag {
65    ($diagnostics:expr, $($arg:tt)*) => {{
66        return Err($diagnostics
67            .diagnostic(midenc_session::diagnostics::Severity::Error)
68            .with_message(format!($($arg)*))
69            .into_report());
70    }}
71}