use std::{borrow::Cow, fmt, ops::Range};
pub const DEFAULT_INPUT_PREVIEW: usize = 80;
#[must_use]
pub fn preview_input(input: &str, max_chars: usize) -> String {
if max_chars == 0 {
return String::new();
}
let mut cut_at = input.len();
for (char_count, (idx, _)) in input.char_indices().enumerate() {
if char_count == max_chars {
cut_at = idx;
break;
}
}
if cut_at == input.len() {
input.to_owned()
} else {
let mut preview = String::with_capacity(cut_at + 3);
preview.push_str(&input[..cut_at]);
preview.push_str("...");
preview
}
}
pub type ParseResult<T> = Result<T, ParseError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct SourceSpan {
pub start: usize,
pub end: usize,
}
impl PartialEq<Range<usize>> for SourceSpan {
fn eq(&self, other: &Range<usize>) -> bool {
self.start == other.start && self.end == other.end
}
}
impl SourceSpan {
#[must_use]
pub const fn new(start: usize, end: usize) -> Self {
if end < start {
Self { start, end: start }
} else {
Self { start, end }
}
}
#[must_use]
pub const fn from_start_len(start: usize, len: usize) -> Self {
Self::new(start, start.saturating_add(len))
}
#[must_use]
pub const fn range(range: Range<usize>) -> Self {
Self::new(range.start, range.end)
}
#[must_use]
pub const fn point(offset: usize) -> Self {
Self {
start: offset,
end: offset,
}
}
#[must_use]
pub const fn len(self) -> usize {
self.end.saturating_sub(self.start)
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.start == self.end
}
#[must_use]
pub fn line_col(self, source: &str) -> (usize, usize) {
let mut safe_start = self.start.min(source.len());
while safe_start > 0 && !source.is_char_boundary(safe_start) {
safe_start -= 1;
}
let mut line = 1usize;
let mut col = 1usize;
for ch in source[..safe_start].chars() {
if ch == '\n' {
line += 1;
col = 1;
} else {
col += 1;
}
}
(line, col)
}
}
impl From<Range<usize>> for SourceSpan {
fn from(range: Range<usize>) -> Self {
Self::range(range)
}
}
impl fmt::Display for SourceSpan {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_empty() {
write!(f, "offset {}", self.start)
} else {
write!(f, "offsets {}..{}", self.start, self.end)
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
UnexpectedToken {
expected: &'static str,
found: String,
},
UnexpectedEOF,
Custom(Cow<'static, str>),
Fatal(Box<ParseError>),
WithSpan {
span: SourceSpan,
source: Box<ParseError>,
},
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::UnexpectedToken { expected, found } => {
let found = preview_input(found, DEFAULT_INPUT_PREVIEW);
write!(
f,
"unexpected token: expected '{expected}', found '{found}'"
)
}
ParseError::UnexpectedEOF => write!(f, "unexpected end of input"),
ParseError::Custom(msg) => write!(f, "{msg}"),
ParseError::Fatal(source) => write!(f, "fatal: {source}"),
ParseError::WithSpan { span, source } => write!(f, "{source} at {span}"),
}
}
}
impl std::error::Error for ParseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ParseError::WithSpan { source, .. } | ParseError::Fatal(source) => Some(source),
_ => None,
}
}
}
impl ParseError {
#[must_use]
pub fn custom<S: Into<Cow<'static, str>>>(msg: S) -> Self {
ParseError::Custom(msg.into())
}
#[must_use]
pub fn custom_at<S: Into<Cow<'static, str>>>(msg: S, span: SourceSpan) -> Self {
Self::custom(msg).with_span(span)
}
#[must_use]
pub fn unexpected_token(expected: &'static str, found: &str) -> Self {
ParseError::UnexpectedToken {
expected,
found: preview_input(found, DEFAULT_INPUT_PREVIEW),
}
}
#[must_use]
pub fn fatal<S: Into<Cow<'static, str>>>(msg: S) -> Self {
ParseError::Fatal(Box::new(ParseError::custom(msg)))
}
#[must_use]
pub fn into_fatal(self) -> Self {
match self {
ParseError::Fatal(_) => self,
inner => ParseError::Fatal(Box::new(inner)),
}
}
#[must_use]
pub fn is_fatal(&self) -> bool {
match self {
ParseError::Fatal(_) => true,
ParseError::WithSpan { source, .. } => source.is_fatal(),
_ => false,
}
}
#[must_use]
pub fn with_span(self, span: SourceSpan) -> Self {
match self {
ParseError::WithSpan { .. } => self,
source => ParseError::WithSpan {
span,
source: Box::new(source),
},
}
}
#[must_use]
pub fn at(self, span: SourceSpan) -> Self {
self.with_span(span)
}
#[must_use]
pub fn span(&self) -> Option<SourceSpan> {
match self {
ParseError::WithSpan { span, .. } => Some(*span),
ParseError::Fatal(source) => source.span(),
_ => None,
}
}
#[must_use]
pub fn farthest(self, other: ParseError) -> ParseError {
match (self.span(), other.span()) {
(Some(left), Some(right)) => {
if right.start > left.start {
other
} else if right.start < left.start {
self
} else if right.end > left.end {
other
} else if right.end < left.end {
self
} else {
other
}
}
(Some(_), None) => self,
(None, _) => other,
}
}
#[must_use]
pub fn root_cause(&self) -> &ParseError {
match self {
ParseError::WithSpan { source, .. } | ParseError::Fatal(source) => source.root_cause(),
_ => self,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_display_unexpected_token() {
let err = ParseError::UnexpectedToken {
expected: "let",
found: "foo".to_string(),
};
assert_eq!(
format!("{}", err),
"unexpected token: expected 'let', found 'foo'"
);
}
#[test]
fn test_error_display_eof() {
let err = ParseError::UnexpectedEOF;
assert_eq!(format!("{}", err), "unexpected end of input");
}
#[test]
fn test_error_display_custom() {
let err = ParseError::custom("something went wrong");
assert_eq!(format!("{}", err), "something went wrong");
}
#[test]
fn test_error_display_with_span() {
let err = ParseError::custom("something went wrong").with_span(SourceSpan::new(3, 6));
assert_eq!(format!("{}", err), "something went wrong at offsets 3..6");
}
#[test]
fn test_preview_input_truncates_long_values() {
let input = "abcdefghijklmnopqrstuvwxyz";
let preview = preview_input(input, 5);
assert_eq!(preview, "abcde...");
}
#[test]
fn test_preview_input_keeps_short_values() {
let input = "short";
let preview = preview_input(input, 10);
assert_eq!(preview, "short");
}
#[test]
fn test_error_custom() {
let err = ParseError::custom("test error");
assert_eq!(err, ParseError::Custom(Cow::Borrowed("test error")));
}
#[test]
fn test_error_span_accessors() {
let err = ParseError::UnexpectedEOF.with_span(SourceSpan::point(10));
assert_eq!(err.span(), Some(SourceSpan::point(10)));
assert_eq!(err.root_cause(), &ParseError::UnexpectedEOF);
}
#[test]
fn test_error_farthest_prefers_later_span() {
let left = ParseError::custom("left").with_span(SourceSpan::point(3));
let right = ParseError::custom("right").with_span(SourceSpan::point(7));
assert_eq!(left.farthest(right.clone()), right);
}
#[test]
fn test_error_farthest_prefers_spanned_error() {
let left = ParseError::custom("left").with_span(SourceSpan::point(3));
let right = ParseError::custom("right");
assert_eq!(left.clone().farthest(right), left);
}
#[test]
fn test_error_farthest_prefers_other_on_tie() {
let left = ParseError::custom("left").with_span(SourceSpan::new(3, 5));
let right = ParseError::custom("right").with_span(SourceSpan::new(3, 5));
assert_eq!(left.farthest(right.clone()), right);
}
#[test]
fn test_source_span_line_col() {
let source = "a\nxyz\nrest";
let span = SourceSpan::point(4);
assert_eq!(span.line_col(source), (2, 3));
}
#[test]
fn test_fatal_constructor_marks_is_fatal() {
let err = ParseError::fatal("boom");
assert!(err.is_fatal());
assert_eq!(err.root_cause(), &ParseError::Custom(Cow::Borrowed("boom")));
}
#[test]
fn test_into_fatal_is_idempotent() {
let once = ParseError::custom("boom").into_fatal();
let twice = once.clone().into_fatal();
assert_eq!(once, twice);
assert!(twice.is_fatal());
}
#[test]
fn test_fatal_span_is_transparent_either_way() {
let span = SourceSpan::point(7);
let a = ParseError::custom("x").with_span(span).into_fatal();
let b = ParseError::fatal("x").with_span(span);
assert_eq!(a.span(), Some(span));
assert_eq!(b.span(), Some(span));
assert!(a.is_fatal());
assert!(b.is_fatal());
}
#[test]
fn test_unexpected_token_constructor_truncates_found() {
let long = "x".repeat(DEFAULT_INPUT_PREVIEW + 50);
let err = ParseError::unexpected_token("literal", &long);
match err {
ParseError::UnexpectedToken { found, .. } => {
assert!(found.ends_with("..."));
assert!(found.len() < long.len());
}
other => panic!("unexpected variant: {other:?}"),
}
}
}