use core::fmt;
pub type RsonResult<T> = Result<T, RsonError>;
#[derive(Debug, Clone, PartialEq)]
pub enum RsonError {
SyntaxError {
message: String,
line: usize,
column: usize,
},
UnexpectedEof,
InvalidCharacter {
found: char,
expected: String,
position: usize,
},
InvalidNumber(String),
InvalidEscape(String),
InvalidUnicode(String),
InvalidIdentifier(String),
TypeMismatch {
expected: String,
found: String,
},
IndexOutOfBounds(usize),
KeyNotFound(String),
Custom(String),
}
impl RsonError {
pub fn syntax_error<S: Into<String>>(message: S, line: usize, column: usize) -> Self {
RsonError::SyntaxError {
message: message.into(),
line,
column,
}
}
pub fn invalid_character<S: Into<String>>(found: char, expected: S, position: usize) -> Self {
RsonError::InvalidCharacter {
found,
expected: expected.into(),
position,
}
}
pub fn type_mismatch<S: Into<String>>(expected: S, found: S) -> Self {
RsonError::TypeMismatch {
expected: expected.into(),
found: found.into(),
}
}
pub fn custom<S: Into<String>>(message: S) -> Self {
RsonError::Custom(message.into())
}
}
impl fmt::Display for RsonError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RsonError::SyntaxError { message, line, column } => {
write!(f, "Syntax error at line {}, column {}: {}", line, column, message)
}
RsonError::UnexpectedEof => {
write!(f, "Unexpected end of input")
}
RsonError::InvalidCharacter { found, expected, position } => {
write!(f, "Invalid character '{}' at position {}, expected {}", found, position, expected)
}
RsonError::InvalidNumber(msg) => {
write!(f, "Invalid number: {}", msg)
}
RsonError::InvalidEscape(msg) => {
write!(f, "Invalid escape sequence: {}", msg)
}
RsonError::InvalidUnicode(msg) => {
write!(f, "Invalid Unicode: {}", msg)
}
RsonError::InvalidIdentifier(msg) => {
write!(f, "Invalid identifier: {}", msg)
}
RsonError::TypeMismatch { expected, found } => {
write!(f, "Type mismatch: expected {}, found {}", expected, found)
}
RsonError::IndexOutOfBounds(index) => {
write!(f, "Index {} out of bounds", index)
}
RsonError::KeyNotFound(key) => {
write!(f, "Key '{}' not found", key)
}
RsonError::Custom(msg) => {
write!(f, "{}", msg)
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for RsonError {}
impl From<nom::Err<nom::error::Error<&str>>> for RsonError {
fn from(err: nom::Err<nom::error::Error<&str>>) -> Self {
match err {
nom::Err::Incomplete(_) => RsonError::UnexpectedEof,
nom::Err::Error(e) | nom::Err::Failure(e) => {
RsonError::Custom(format!("Parse error: {:?}", e))
}
}
}
}
impl From<nom::Err<nom::error::VerboseError<&str>>> for RsonError {
fn from(err: nom::Err<nom::error::VerboseError<&str>>) -> Self {
match err {
nom::Err::Incomplete(_) => RsonError::UnexpectedEof,
nom::Err::Error(e) | nom::Err::Failure(e) => {
let msg = nom::error::convert_error("", e);
RsonError::Custom(format!("Parse error: {}", msg))
}
}
}
}