#[cfg(feature = "std")]
use std::fmt;
#[cfg(not(feature = "std"))]
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error as StdError;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
Syntax {
message: String,
line: Option<usize>,
column: Option<usize>,
},
UnexpectedChar {
found: char,
expected: String,
position: Option<usize>,
},
UnexpectedEof {
expected: String,
},
InvalidEscape {
sequence: String,
position: Option<usize>,
},
InvalidUnicode {
sequence: String,
position: Option<usize>,
},
InvalidNumber {
value: String,
reason: String,
},
LimitExceeded {
limit_type: String,
limit: usize,
},
Message(String),
}
impl ParseError {
pub fn syntax(message: impl Into<String>, line: Option<usize>, column: Option<usize>) -> Self {
ParseError::Syntax {
message: message.into(),
line,
column,
}
}
pub fn unexpected_char(found: char, expected: impl Into<String>) -> Self {
ParseError::UnexpectedChar {
found,
expected: expected.into(),
position: None,
}
}
pub fn unexpected_eof(expected: impl Into<String>) -> Self {
ParseError::UnexpectedEof {
expected: expected.into(),
}
}
pub fn limit_exceeded(limit_type: impl Into<String>, limit: usize) -> Self {
ParseError::LimitExceeded {
limit_type: limit_type.into(),
limit,
}
}
pub fn message(msg: impl Into<String>) -> Self {
ParseError::Message(msg.into())
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::Syntax { message, line, column } => {
write!(f, "Syntax error: {}", message)?;
if let (Some(line), Some(col)) = (line, column) {
write!(f, " at line {}, column {}", line, col)?;
} else if let Some(line) = line {
write!(f, " at line {}", line)?;
}
Ok(())
}
ParseError::UnexpectedChar { found, expected, position } => {
write!(f, "Unexpected character '{}', expected {}", found, expected)?;
if let Some(pos) = position {
write!(f, " at position {}", pos)?;
}
Ok(())
}
ParseError::UnexpectedEof { expected } => {
write!(f, "Unexpected end of input, expected {}", expected)
}
ParseError::InvalidEscape { sequence, position } => {
write!(f, "Invalid escape sequence '{}'", sequence)?;
if let Some(pos) = position {
write!(f, " at position {}", pos)?;
}
Ok(())
}
ParseError::InvalidUnicode { sequence, position } => {
write!(f, "Invalid Unicode escape sequence '{}'", sequence)?;
if let Some(pos) = position {
write!(f, " at position {}", pos)?;
}
Ok(())
}
ParseError::InvalidNumber { value, reason } => {
write!(f, "Invalid number '{}': {}", value, reason)
}
ParseError::LimitExceeded { limit_type, limit } => {
write!(f, "Maximum {} of {} exceeded", limit_type, limit)
}
ParseError::Message(msg) => write!(f, "{}", msg),
}
}
}
#[cfg(feature = "std")]
impl StdError for ParseError {}
impl From<String> for ParseError {
fn from(s: String) -> Self {
ParseError::Message(s)
}
}
impl From<&str> for ParseError {
fn from(s: &str) -> Self {
ParseError::Message(s.into())
}
}
impl From<ParseError> for String {
fn from(e: ParseError) -> Self {
e.to_string()
}
}
impl From<ParseError> for babbel_core::BabbelError {
fn from(err: ParseError) -> Self {
let (code, msg, span) = match &err {
ParseError::Syntax { message, line, column } => {
let span = line.map(|l| babbel_core::Span::new(
babbel_core::Location::new(l, column.unwrap_or(1), 0),
babbel_core::Location::new(l, column.unwrap_or(1), 0),
));
(babbel_core::ErrorCode::SyntaxError, message.clone(), span)
}
ParseError::UnexpectedEof { expected } => {
#[cfg(feature = "alloc")]
let m = alloc::format!("unexpected EOF, expected {expected}");
#[cfg(not(feature = "alloc"))]
let m = expected.clone();
(babbel_core::ErrorCode::UnexpectedEof, m, None)
}
ParseError::UnexpectedChar { found, expected, position } => {
let span = position.map(|p| babbel_core::Span::new(
babbel_core::Location::new(1, p + 1, p),
babbel_core::Location::new(1, p + 1, p),
));
#[cfg(feature = "alloc")]
let m = alloc::format!("unexpected character '{found}', expected {expected}");
#[cfg(not(feature = "alloc"))]
let m = expected.clone();
(babbel_core::ErrorCode::SyntaxError, m, span)
}
ParseError::InvalidEscape { sequence, position } => {
let span = position.map(|p| babbel_core::Span::new(
babbel_core::Location::new(1, p + 1, p),
babbel_core::Location::new(1, p + 1, p),
));
#[cfg(feature = "alloc")]
let m = alloc::format!("invalid escape sequence '{sequence}'");
#[cfg(not(feature = "alloc"))]
let m = sequence.clone();
(babbel_core::ErrorCode::SyntaxError, m, span)
}
ParseError::InvalidUnicode { sequence, position } => {
let span = position.map(|p| babbel_core::Span::new(
babbel_core::Location::new(1, p + 1, p),
babbel_core::Location::new(1, p + 1, p),
));
#[cfg(feature = "alloc")]
let m = alloc::format!("invalid Unicode escape '{sequence}'");
#[cfg(not(feature = "alloc"))]
let m = sequence.clone();
(babbel_core::ErrorCode::InvalidEncoding, m, span)
}
ParseError::InvalidNumber { value, reason } => {
#[cfg(feature = "alloc")]
let m = alloc::format!("invalid number '{value}': {reason}");
#[cfg(not(feature = "alloc"))]
let m = reason.clone();
(babbel_core::ErrorCode::SyntaxError, m, None)
}
_ => (babbel_core::ErrorCode::Custom, err.to_string(), None),
};
let mut berr = babbel_core::BabbelError::new(code, msg).with_format("json");
if let Some(s) = span {
berr = berr.with_span(s);
}
berr
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_syntax_error() {
let err = ParseError::syntax("Invalid JSON", Some(5), Some(10));
let s = err.to_string();
assert!(s.contains("Syntax error"));
assert!(s.contains("line 5"));
assert!(s.contains("column 10"));
}
#[test]
fn test_unexpected_char() {
let err = ParseError::unexpected_char('}', "comma or closing bracket");
let s = err.to_string();
assert!(s.contains("Unexpected character '}'"));
assert!(s.contains("expected comma or closing bracket"));
}
#[test]
fn test_limit_exceeded() {
let err = ParseError::limit_exceeded("nesting depth", 100);
let s = err.to_string();
assert!(s.contains("Maximum nesting depth"));
assert!(s.contains("100"));
}
#[test]
fn test_from_string() {
let err: ParseError = "Something went wrong".into();
assert!(matches!(err, ParseError::Message(_)));
}
#[test]
fn test_to_string() {
let err = ParseError::message("Test error");
let s: String = err.into();
assert_eq!(s, "Test error");
}
}