use std::fmt::{self, Display};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ParserError {
#[error("one or more parsing errors occurred:\n{}", .report)]
SyntaxError {
report: ParseErrorReport,
},
#[error(
"unexpected error in the parser; please report this issue at {}",
crate::error::BUG_REPORT_URL
)]
InternalNomError {
#[from]
#[source]
source: nom::error::Error<String>,
},
}
#[derive(Debug)]
pub struct ParseErrorReport {
errors: Vec<ParseError>,
}
impl Display for ParseErrorReport {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for error in self.errors() {
writeln!(f, "{error}\n")?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct ParseError {
pub start_idx: usize,
pub len: usize,
}
impl Display for ParseError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid tokens of length {} at position {} ",
self.len, self.start_idx
)
}
}
impl ParseError {
fn end_idx(&self) -> usize {
self.start_idx + self.len - 1
}
}
impl ParseErrorReport {
pub(crate) fn new() -> Self {
Self { errors: vec![] }
}
pub(crate) fn record_at(&mut self, idx: usize) {
match self.errors.last_mut() {
Some(last_error) if last_error.end_idx() + 1 == idx => last_error.len += 1,
_ => self.add_new(idx),
}
}
#[inline]
pub fn errors(&self) -> impl Iterator<Item = &ParseError> {
self.errors.iter()
}
fn add_new(&mut self, idx: usize) {
self.errors.push(ParseError {
start_idx: idx,
len: 1,
})
}
}
#[derive(Debug, Error)]
pub enum CompilerError {
#[error(transparent)]
NotSupportedError(#[from] crate::error::UnsupportedFeatureError),
}