use std::{fmt, io};
use crate::span::Span;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum ErrorKind {
Io(io::Error),
Lex(String),
Parse(String),
Runtime(String),
}
#[derive(Debug)]
pub struct Error {
pub kind: ErrorKind,
pub span: Option<Span>,
pub file: Option<String>,
}
impl Error {
pub fn io(err: io::Error, file: Option<String>) -> Self {
Self { kind: ErrorKind::Io(err), span: None, file }
}
pub fn lex(msg: impl Into<String>, file: Option<String>, span: Option<Span>) -> Self {
Self { kind: ErrorKind::Lex(msg.into()), span, file }
}
pub fn parse(msg: impl Into<String>, file: Option<String>, span: Option<Span>) -> Self {
Self { kind: ErrorKind::Parse(msg.into()), span, file }
}
pub fn runtime(msg: impl Into<String>, file: Option<String>, span: Option<Span>) -> Self {
Self { kind: ErrorKind::Runtime(msg.into()), span, file }
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (k, msg) = match &self.kind {
ErrorKind::Io(e) => ("io", e.to_string()),
ErrorKind::Lex(s) => ("lex", s.clone()),
ErrorKind::Parse(s) => ("parse", s.clone()),
ErrorKind::Runtime(s) => ("runtime", s.clone()),
};
match (&self.file, &self.span) {
(Some(file), Some(span)) => {
write!(f, "{k} {file}:{}..{}: {msg}", span.start, span.end)
}
(Some(file), None) => write!(f, "{k} {file}: {msg}"),
(None, Some(span)) => write!(f, "{k} {}..{}: {msg}", span.start, span.end),
(None, None) => write!(f, "{k} {msg}"),
}
}
}
impl std::error::Error for Error {}
impl From<io::Error> for Error {
fn from(value: io::Error) -> Self {
Error { kind: ErrorKind::Io(value), span: None, file: None }
}
}