use std::fmt;
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
pub line: usize,
pub col: usize,
pub message: String,
pub context: String,
}
impl ParseError {
pub(crate) fn at(source: &str, offset: usize, message: impl Into<String>) -> Self {
let (line, col) = line_col(source, offset);
let context = source_line(source, line).to_string();
ParseError {
line,
col,
message: message.into(),
context,
}
}
pub(crate) fn detached(message: impl Into<String>) -> Self {
ParseError {
line: 0,
col: 0,
message: message.into(),
context: String::new(),
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.line == 0 {
write!(f, "{}", self.message)
} else {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
}
impl std::error::Error for ParseError {}
#[derive(Debug)]
pub enum Error {
Parse(ParseError),
Io {
path: std::path::PathBuf,
source: std::io::Error,
},
}
impl Error {
pub(crate) fn parse(e: ParseError) -> Self {
Error::Parse(e)
}
pub(crate) fn io(path: &Path, source: std::io::Error) -> Self {
Error::Io {
path: path.to_path_buf(),
source,
}
}
pub fn detached(msg: impl Into<String>) -> Self {
Error::Parse(ParseError::detached(msg))
}
pub fn as_parse(&self) -> Option<&ParseError> {
match self {
Error::Parse(e) => Some(e),
Error::Io { .. } => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Parse(e) => write!(f, "{}", e),
Error::Io { path, source } => {
write!(f, "failed to read {}: {}", path.display(), source)
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Parse(e) => Some(e),
Error::Io { source, .. } => Some(source),
}
}
}
impl From<ParseError> for Error {
fn from(e: ParseError) -> Self {
Error::Parse(e)
}
}
pub(crate) fn line_col(source: &str, offset: usize) -> (usize, usize) {
let offset = offset.min(source.len());
let before = &source[..offset];
let line = before.bytes().filter(|&b| b == b'\n').count() + 1;
let line_start = before.rfind('\n').map(|i| i + 1).unwrap_or(0);
let col = before[line_start..].chars().count() + 1;
(line, col)
}
pub(crate) fn source_line(source: &str, line: usize) -> &str {
source.lines().nth(line.saturating_sub(1)).unwrap_or("")
}