Skip to main content

tinywasm_parser/
error.rs

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