use std::fmt;
use std::ops::Range;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
pub struct ParseError {
pub span: Range<usize>,
pub span_utf16: Range<usize>,
pub line: usize,
pub column: usize,
pub found: Option<String>,
pub expected: &'static [&'static str],
#[cfg_attr(
feature = "serialize",
serde(skip_serializing_if = "std::ops::Not::not")
)]
pub reserved: bool,
#[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
pub hint: Option<&'static str>,
}
impl ParseError {
pub(crate) fn new(input: &str, at: usize, expected: &'static [&'static str]) -> Self {
let end = at + input[at..].chars().next().map_or(0, char::len_utf8);
Self::spanning(input, at..end, expected)
}
pub(crate) fn spanning(
input: &str,
span: Range<usize>,
expected: &'static [&'static str],
) -> Self {
let before = &input[..span.start];
let found = &input[span.clone()];
let start_of_line = before.rfind('\n').map_or(0, |n| n + 1);
let utf16 = |text: &str| text.chars().map(char::len_utf16).sum::<usize>();
let start_utf16 = utf16(before);
Self {
span_utf16: start_utf16..start_utf16 + utf16(found),
line: before.matches('\n').count() + 1,
column: before[start_of_line..].chars().count() + 1,
found: (!found.is_empty()).then(|| found.to_owned()),
span,
expected,
reserved: false,
hint: None,
}
}
#[must_use]
pub(crate) fn with_hint(self, hint: &'static str) -> Self {
Self {
hint: Some(hint),
..self
}
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.found {
Some(word) if self.reserved => {
write!(
f,
"{word:?}, a word reserved for a later version of the syntax,"
)?;
}
Some(token) => write!(f, "unexpected {token:?}")?,
None => f.write_str("unexpected end of input")?,
}
write!(f, " at line {}, character {}", self.line, self.column)?;
if !self.expected.is_empty() {
write!(f, ", expected {}", super::or_list(self.expected))?;
}
if let Some(hint) = self.hint {
write!(f, ": {hint}")?;
}
Ok(())
}
}
impl std::error::Error for ParseError {}