//! Parser result types. use std::fmt; use std::path::PathBuf; use std::rc::Rc; /// A location in a string. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Location { /// Byte index (0-indexed). pub index: usize, /// Line (1-indexed). pub line: usize, /// Column (1-indexed). pub column: usize, } impl Default for Location { fn default() -> Self { Self { index: 0, line: 1, column: 1, } } } /// A sub-string at a specific location. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Cursor<'a> { /// The input string reference. pub input: &'a str, /// The location of the string reference in the string. pub location: Location, } impl<'a> Cursor<'a> { /// Create a new cursor. pub fn new(input: &'a str, location: Location) -> Self { Self { input, location } } /// Advance the cursor by consuming `n` characters. pub fn advance(&self, n: usize) -> Self { let mut loc = self.location; let mut chars = self.input.chars(); for _ in 0..n { // SAFETY: Since this function should only be called to consume // input that we have already peeked at, a missing character // indicates a bug. let ch = chars.next().expect("Cursor::advance: unexpected end of input"); if ch == '\n' { loc.line += 1; loc.column = 1; } else { loc.column += 1; } loc.index += ch.len_utf8(); } Self { input: chars.as_str(), location: loc, } } } impl<'a> From<&'a str> for Cursor<'a> { fn from(input: &'a str) -> Self { Self { input, location: Location::default(), } } } /// Result of applying a `Parser` to an input. pub type Result<'a, T> = std::result::Result<(T, Cursor<'a>), Error<'a>>; /// The specific type of parser error that occurred. #[derive(Debug, Clone)] pub enum ErrorKind<'a> { /// Expected end of input but found more content. ExpectedEof, /// Expected a specific character. ExpectedChar(char), /// Expected a specific string. ExpectedString(&'a str), /// Expected one of several possible values. ExpectedOneOf(Vec>), /// Expected something described by the string. ExpectedOther(Rc), /// A custom error message. Custom(Rc), /// Error converting from string using FromStr. FromStr(Rc), /// Error mapping a value using try_map. TryMap(Rc), /// Found an unexpected character. UnexpectedChar(char), /// Found unexpected end of input. UnexpectedEof, } impl PartialEq for ErrorKind<'_> { fn eq(&self, other: &Self) -> bool { use ErrorKind::*; match (self, other) { (ExpectedEof, ExpectedEof) => true, (ExpectedChar(a), ExpectedChar(b)) => a == b, (ExpectedString(a), ExpectedString(b)) => a == b, (ExpectedOneOf(a), ExpectedOneOf(b)) => a == b, (FromStr(a), FromStr(b)) => Rc::ptr_eq(a, b), (TryMap(a), TryMap(b)) => Rc::ptr_eq(a, b), (ExpectedOther(a), ExpectedOther(b)) => a == b, (UnexpectedChar(a), UnexpectedChar(b)) => a == b, (UnexpectedEof, UnexpectedEof) => true, _ => false, } } } impl Eq for ErrorKind<'_> {} /// A parser error. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Error<'a> { /// Error message (without source location). pub kind: ErrorKind<'a>, /// The place in the input where the error occurred. pub cursor: Cursor<'a>, /// File path of the source. pub path: Option, } impl<'a> Error<'a> { /// Create a new parser error from a message. pub fn new(kind: ErrorKind<'a>, cursor: Cursor<'a>) -> Self { Self { kind, cursor, path: None, } } /// Returns the unparsed portion of the input at the error location pub fn unparsed(&self) -> &'a str { self.cursor.input } /// Returns a description of what was expected, if applicable pub fn expected(&self) -> Option> { match &self.kind { ErrorKind::ExpectedChar(c) => Some(c.to_string().into()), ErrorKind::ExpectedString(s) => Some((*s).into()), ErrorKind::ExpectedOther(s) => Some(s.clone()), ErrorKind::ExpectedEof => Some("end of file".into()), _ => None, } } /// Returns a formatted error message including file location and details pub fn explain(&self) -> String { format!( "{}:{}:{}: error: {}", self.path .as_ref() .map(|p| p.display().to_string()) .unwrap_or("".to_owned()), self.cursor.location.line, self.cursor.location.column, self, ) } } impl std::fmt::Display for Error<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let input = self.cursor.input; let eof = input.is_empty(); let actual = input .find('\n') .map(|i| if i > 0 { &input[..i] } else { "\n" }) .unwrap_or(input); match &self.kind { ErrorKind::ExpectedEof => { write!(f, "expected end-of-input, got `{actual}`") } ErrorKind::ExpectedChar(c) => { if eof { write!(f, "expected '{c}', got end-of-input") } else { write!(f, "expected '{c}', got `{actual}`") } } ErrorKind::ExpectedString(s) => { if eof { write!(f, "expected `{s}`, got end-of-input") } else { write!(f, "expected `{s}`, got `{actual}`") } } ErrorKind::ExpectedOther(expected) => { if eof { write!(f, "expected {expected}, got end-of-input") } else { write!(f, "expected {expected}, got `{actual}`") } } ErrorKind::ExpectedOneOf(expected) => { let choices = expected .iter() .map(|c| format!("`{c}`")) .collect::>() .join(", "); if eof { write!(f, "expected one of {choices}, got end-of-input") } else { write!(f, "expected one of {choices}, got `{actual}`") } } ErrorKind::Custom(err) => { write!(f, "{err}") } ErrorKind::FromStr(e) => { write!(f, "string conversion failed: {e}") } ErrorKind::TryMap(e) => { write!(f, "value conversion failed: {e}") } ErrorKind::UnexpectedEof => { write!(f, "unexpected end-of-input") } ErrorKind::UnexpectedChar(c) => { write!(f, "unexpected '{c}'") } } } } impl std::error::Error for Error<'_> {}