use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ErrorKind {
Syntax,
Unsupported,
Type,
Runtime,
Limit,
}
#[derive(Clone, Debug)]
pub struct Error {
kind: ErrorKind,
offset: Option<usize>,
message: String,
}
impl Error {
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
offset: None,
message: message.into(),
}
}
#[must_use]
pub fn with_offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
pub(crate) fn shift(self, base: usize) -> Self {
match self.offset {
Some(o) => Self {
offset: Some(o.saturating_add(base)),
..self
},
None => self,
}
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn offset(&self) -> Option<usize> {
self.offset
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.offset {
Some(off) => write!(f, "{:?} @{}: {}", self.kind, off, self.message),
None => write!(f, "{:?}: {}", self.kind, self.message),
}
}
}
impl std::error::Error for Error {}