use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PvgErrorKind {
Lex,
Parse,
Runtime,
SafetyLimit,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PvgError {
pub kind: PvgErrorKind,
pub message: String,
pub line: Option<usize>,
pub col: Option<usize>,
}
impl PvgError {
pub fn lex(line: usize, col: usize, msg: impl Into<String>) -> Self {
Self {
kind: PvgErrorKind::Lex,
message: msg.into(),
line: Some(line),
col: Some(col),
}
}
pub fn parse(line: usize, col: usize, msg: impl Into<String>) -> Self {
Self {
kind: PvgErrorKind::Parse,
message: msg.into(),
line: Some(line),
col: Some(col),
}
}
pub fn parse_line(line: usize, msg: impl Into<String>) -> Self {
Self {
kind: PvgErrorKind::Parse,
message: msg.into(),
line: Some(line),
col: None,
}
}
pub fn runtime(msg: impl Into<String>) -> Self {
Self {
kind: PvgErrorKind::Runtime,
message: msg.into(),
line: None,
col: None,
}
}
pub fn safety_limit(msg: impl Into<String>) -> Self {
Self {
kind: PvgErrorKind::SafetyLimit,
message: msg.into(),
line: None,
col: None,
}
}
}
impl fmt::Display for PvgError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (self.line, self.col) {
(Some(l), Some(c)) => write!(f, "Line {}, Col {}: {}", l, c, self.message),
(Some(l), None) => write!(f, "Line {}: {}", l, self.message),
(None, _) => write!(f, "{}", self.message),
}
}
}
impl std::error::Error for PvgError {}
impl From<PvgError> for String {
fn from(err: PvgError) -> Self {
err.to_string()
}
}
impl From<String> for PvgError {
fn from(msg: String) -> Self {
PvgError::runtime(msg)
}
}
impl From<&str> for PvgError {
fn from(msg: &str) -> Self {
PvgError::runtime(msg)
}
}