tinywasm_parser/
error.rs

1use core::fmt::{Debug, Display};
2
3use alloc::string::{String, ToString};
4use wasmparser::Encoding;
5
6#[derive(Debug)]
7/// Errors that can occur when parsing a WebAssembly module
8pub enum ParseError {
9    /// An invalid type was encountered
10    InvalidType,
11    /// An unsupported section was encountered
12    UnsupportedSection(String),
13    /// A duplicate section was encountered
14    DuplicateSection(String),
15    /// An empty section was encountered
16    EmptySection(String),
17    /// An unsupported operator was encountered
18    UnsupportedOperator(String),
19    /// An error occurred while parsing the module
20    ParseError {
21        /// The error message
22        message: String,
23        /// The offset in the module where the error occurred
24        offset: usize,
25    },
26    /// An invalid encoding was encountered
27    InvalidEncoding(Encoding),
28    /// An invalid local count was encountered
29    InvalidLocalCount {
30        /// The expected local count
31        expected: u32,
32        /// The actual local count
33        actual: u32,
34    },
35    /// The end of the module was not reached
36    EndNotReached,
37    /// An unknown error occurred
38    Other(String),
39}
40
41impl Display for ParseError {
42    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
43        match self {
44            Self::InvalidType => write!(f, "invalid type"),
45            Self::UnsupportedSection(section) => write!(f, "unsupported section: {section}"),
46            Self::DuplicateSection(section) => write!(f, "duplicate section: {section}"),
47            Self::EmptySection(section) => write!(f, "empty section: {section}"),
48            Self::UnsupportedOperator(operator) => write!(f, "unsupported operator: {operator}"),
49            Self::ParseError { message, offset } => {
50                write!(f, "error parsing module: {message} at offset {offset}")
51            }
52            Self::InvalidEncoding(encoding) => write!(f, "invalid encoding: {encoding:?}"),
53            Self::InvalidLocalCount { expected, actual } => {
54                write!(f, "invalid local count: expected {expected}, actual {actual}")
55            }
56            Self::EndNotReached => write!(f, "end of module not reached"),
57            Self::Other(message) => write!(f, "unknown error: {message}"),
58        }
59    }
60}
61
62#[cfg(any(feature = "std", all(not(feature = "std"), feature = "nightly")))]
63impl crate::std::error::Error for ParseError {}
64
65impl From<wasmparser::BinaryReaderError> for ParseError {
66    fn from(value: wasmparser::BinaryReaderError) -> Self {
67        Self::ParseError { message: value.message().to_string(), offset: value.offset() }
68    }
69}
70
71pub(crate) type Result<T, E = ParseError> = core::result::Result<T, E>;