1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use crate::source::describe_position;
use std::fmt;
use std::str::Utf8Error;

#[cfg_attr(test, derive(Debug))]
pub enum ErrorKind {
    IntOverflow {
        ty: &'static str,
        got: Option<u64>,
    },
    UnexpectedEof {
        expected: &'static str,
    },
    WasmMagicNotFound,
    VersionMismatch([u8; 4]),
    LengthOutOfInput {
        input: usize,
        specified: usize,
        what: &'static str,
    },
    InvalidUtf8 {
        what: &'static str,
        error: Utf8Error,
    },
    UnexpectedByte {
        expected: Vec<u8>,
        got: u8,
        what: &'static str,
    },
    FuncCodeLengthMismatch {
        num_funcs: usize,
        num_codes: usize,
    },
    TooManyLocalVariables,
    MalformedSectionSize,
    ExpectedEof(u8),
}

#[cfg_attr(test, derive(Debug))]
pub struct Error<'source> {
    pub kind: ErrorKind,
    pub pos: usize,
    pub source: &'source [u8],
    pub when: &'static str,
}

impl<'s> Error<'s> {
    pub(crate) fn new(
        kind: ErrorKind,
        pos: usize,
        source: &'s [u8],
        when: &'static str,
    ) -> Box<Error<'s>> {
        Box::new(Error {
            kind,
            pos,
            source,
            when,
        })
    }
}

impl<'s> fmt::Display for Error<'s> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ErrorKind::*;
        match &self.kind {
            IntOverflow { ty, got: Some(got) } => write!(
                f,
                "LEB128-encoded integer '{:x}' is too large for {} value",
                got, ty
            )?,
            IntOverflow { ty, got: None } => {
                write!(f, "LEB128-encoded integer is too large for {} value", ty)?
            }
            UnexpectedEof { expected } => write!(
                f,
                "expected {} but reached end of current section or input",
                expected
            )?,
            WasmMagicNotFound => write!(
                f,
                "WebAssembly binary must start with magic 0x00 0x61 0x73 0x6d"
            )?,
            VersionMismatch(v) => write!(f, "expected version [1, 0, 0, 0] but got {:?}", v)?,
            LengthOutOfInput {
                input,
                specified,
                what,
            } => write!(
                f,
                "{} ({} bytes) is larger than the rest of input ({} bytes)",
                what, specified, input
            )?,
            InvalidUtf8 { what, error } => write!(f, "{} must be UTF-8 sequence: {}", what, error)?,
            UnexpectedByte {
                expected,
                got,
                what,
            } if expected.is_empty() => write!(f, "unexpected byte 0x{:02x} at {}", got, what,)?,
            UnexpectedByte {
                expected,
                got,
                what,
            } if expected.len() == 1 => write!(
                f,
                "expected byte 0x{:02x} for {} but got 0x{:02x}",
                expected[0], what, got
            )?,
            UnexpectedByte {
                expected,
                got,
                what,
            } => {
                f.write_str("expected one of ")?;
                let mut first = true;
                for b in expected.iter() {
                    if !first {
                        f.write_str(", ")?;
                    }
                    write!(f, "0x{:02x}", b)?;
                    first = false;
                }
                write!(f, " for {} but got byte 0x{:02x}", what, got)?;
            }
            FuncCodeLengthMismatch {
                num_funcs,
                num_codes,
            } => write!(
                f,
                "number of function sections '{}' does not match to number of code sections '{}'",
                num_funcs, num_codes,
            )?,
            TooManyLocalVariables => write!(f, "too many local variables")?,
            MalformedSectionSize => write!(f, "malformed section size")?,
            ExpectedEof(b) => write!(
                f,
                "expected end of input but byte 0x{:02x} is still following",
                b
            )?,
        }
        write!(f, " while parsing {}.", self.when)?;
        describe_position(f, self.source, self.pos)
    }
}

pub type Result<'s, T> = ::std::result::Result<T, Box<Error<'s>>>;