diff --git a/Cargo.toml b/Cargo.toml index 392cfcf..14270f5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "sv-parser", + "sv-parser-error", "sv-parser-macros", "sv-parser-parser", "sv-parser-pp", diff --git a/sv-parser-error/Cargo.toml b/sv-parser-error/Cargo.toml new file mode 100644 index 0000000..25869ed --- /dev/null +++ b/sv-parser-error/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "sv-parser-error" +version = "0.1.0" +authors = ["dalance "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +failure = "*" diff --git a/sv-parser-error/src/lib.rs b/sv-parser-error/src/lib.rs new file mode 100644 index 0000000..d211f8b --- /dev/null +++ b/sv-parser-error/src/lib.rs @@ -0,0 +1,71 @@ +use failure::{Backtrace, Context, Fail}; +use std::fmt; +use std::fmt::Display; +use std::io::Error as IOError; + +// ----------------------------------------------------------------------------- + +#[derive(Fail, Debug)] +pub enum ErrorKind { + #[fail(display = "IO error")] + Io, + #[fail(display = "Parse error")] + Parse, +} + +// ----------------------------------------------------------------------------- + +#[derive(Debug)] +pub struct Error { + inner: Context, +} + +impl Fail for Error { + fn cause(&self) -> Option<&dyn Fail> { + self.inner.cause() + } + + fn backtrace(&self) -> Option<&Backtrace> { + self.inner.backtrace() + } +} + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.inner, f) + } +} + +impl Error { + pub fn new(inner: Context) -> Error { + Error { inner } + } + + pub fn kind(&self) -> &ErrorKind { + self.inner.get_context() + } +} + +impl From for Error { + fn from(kind: ErrorKind) -> Error { + Error { + inner: Context::new(kind), + } + } +} + +impl From> for Error { + fn from(inner: Context) -> Error { + Error { inner } + } +} + +// ----------------------------------------------------------------------------- + +impl From for Error { + fn from(error: IOError) -> Error { + Error { + inner: error.context(ErrorKind::Io), + } + } +}