use std::fmt;
use crate::{Format, ffi};
#[derive(Debug)]
#[cfg_attr(not(feature = "serde"), allow(dead_code))]
#[non_exhaustive]
pub enum Error {
InvalidArgument,
Parse(ParseError),
OutOfMemory,
UnsupportedFormat,
UnsupportedOperation,
NotFound,
Internal,
Utf8,
Number(String),
Message(String),
#[non_exhaustive]
MissingField {
field: &'static str,
ty: &'static str,
},
#[non_exhaustive]
ExpectedMapping { ty: &'static str },
#[non_exhaustive]
UnknownVariant {
enum_name: &'static str,
got: String,
},
#[non_exhaustive]
WrongSeqLen {
label: &'static str,
expected: usize,
got: usize,
},
#[non_exhaustive]
TypeMismatch {
expected: &'static str,
found: &'static str,
},
#[non_exhaustive]
IntOutOfRange { ty: &'static str },
Language(LanguageFailure),
Io(std::io::Error),
#[non_exhaustive]
At { path: String, error: Box<Error> },
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LanguageFailure {
pub message: String,
pub byte_offset: Option<usize>,
}
impl fmt::Display for LanguageFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.byte_offset {
Some(off) => write!(f, "{} (byte offset {off})", self.message),
None => f.write_str(&self.message),
}
}
}
impl std::error::Error for LanguageFailure {}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ParseError {
pub message: String,
pub byte_offset: Option<usize>,
pub line: Option<u32>,
pub column: Option<u32>,
sentence: bool,
}
impl ParseError {
pub(crate) fn from_ffi(e: &ffi::FigError) -> Self {
let len = e.message_len.min(e.message.len());
let message = String::from_utf8_lossy(&e.message[..len]).into_owned();
ParseError {
message,
byte_offset: (e.byte_offset != 0).then_some(e.byte_offset),
line: (e.line != 0).then_some(e.line),
column: (e.column != 0).then_some(e.column),
sentence: false,
}
}
pub(crate) fn generic() -> Self {
Self::sentence(String::from("failed to parse input"))
}
pub(crate) fn refused_edit(format: Format, what: EditTarget) -> Self {
let name = format.name();
Self::sentence(match what {
EditTarget::Value => format!("the new value would not parse as {name}"),
EditTarget::Key => format!("the new key would not parse as {name}"),
EditTarget::Comment => format!("the new comment would not parse as {name}"),
EditTarget::Document => format!("the edited document would not parse as {name}"),
})
}
fn sentence(message: String) -> Self {
ParseError {
message,
byte_offset: None,
line: None,
column: None,
sentence: true,
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum EditTarget {
Value,
Key,
Comment,
Document,
}
pub(crate) fn edit_status(
status: ffi::FigStatus,
format: Format,
what: EditTarget,
) -> Result<(), Error> {
if status == ffi::FigStatus::PARSE_ERROR {
return Err(Error::Parse(ParseError::refused_edit(format, what)));
}
Error::from_status(status)
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.sentence {
f.write_str(&self.message)?;
} else {
write!(f, "failed to parse input: {}", self.message)?;
}
match (self.line, self.column) {
(Some(l), Some(c)) => write!(f, " (line {l}, column {c})"),
_ => match self.byte_offset {
Some(off) => write!(f, " (byte offset {off})"),
None => Ok(()),
},
}
}
}
impl std::error::Error for ParseError {}
impl Error {
#[cold]
#[inline(never)]
pub fn missing_field(field: &'static str, ty: &'static str) -> Self {
Error::MissingField { field, ty }
}
#[cold]
#[inline(never)]
pub fn expected_mapping(ty: &'static str) -> Self {
Error::ExpectedMapping { ty }
}
#[cold]
#[inline(never)]
pub fn unknown_variant(enum_name: &'static str, got: &str) -> Self {
Error::UnknownVariant {
enum_name,
got: got.to_string(),
}
}
#[cold]
#[inline(never)]
pub fn wrong_seq_len(label: &'static str, expected: usize, got: usize) -> Self {
Error::WrongSeqLen {
label,
expected,
got,
}
}
#[cold]
#[inline(never)]
pub fn msg_static(msg: &'static str) -> Self {
Error::Message(msg.to_owned())
}
#[cold]
#[inline(never)]
pub fn type_mismatch(expected: &'static str, found: &'static str) -> Self {
Error::TypeMismatch { expected, found }
}
#[cold]
#[inline(never)]
pub fn int_out_of_range(ty: &'static str) -> Self {
Error::IntOutOfRange { ty }
}
pub(crate) fn from_status(status: ffi::FigStatus) -> Result<(), Self> {
match status {
ffi::FigStatus::OK => Ok(()),
ffi::FigStatus::INVALID_ARGUMENT => Err(Self::InvalidArgument),
ffi::FigStatus::PARSE_ERROR => Err(Self::Parse(ParseError::generic())),
ffi::FigStatus::OUT_OF_MEMORY => Err(Self::OutOfMemory),
ffi::FigStatus::UNSUPPORTED_FORMAT => Err(Self::UnsupportedFormat),
ffi::FigStatus::UNSUPPORTED_OPERATION => Err(Self::UnsupportedOperation),
ffi::FigStatus::NOT_FOUND => Err(Self::NotFound),
_ => Err(Self::Internal),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidArgument => f.write_str("invalid argument"),
Error::Parse(e) => write!(f, "{e}"),
Error::OutOfMemory => f.write_str("out of memory"),
Error::UnsupportedFormat => f.write_str("unsupported format"),
Error::UnsupportedOperation => f.write_str("unsupported operation"),
Error::NotFound => f.write_str("path or region not found"),
Error::Internal => f.write_str("internal error"),
Error::Language(failure) => write!(f, "runtime language: {failure}"),
Error::Utf8 => f.write_str("scalar was not valid UTF-8"),
Error::Number(raw) => write!(f, "invalid number: {raw}"),
Error::Message(msg) => f.write_str(msg),
Error::MissingField { field, ty } => {
write!(f, "missing field `{field}` while building `{ty}`")
}
Error::ExpectedMapping { ty } => write!(f, "expected a mapping to build `{ty}`"),
Error::UnknownVariant { enum_name, got } => {
write!(f, "unknown variant `{got}` for enum `{enum_name}`")
}
Error::WrongSeqLen {
label,
expected,
got,
} => {
write!(
f,
"expected {expected} element(s) for `{label}`, found {got}"
)
}
Error::TypeMismatch { expected, found } => {
write!(f, "expected {expected}, found {found}")
}
Error::IntOutOfRange { ty } => {
write!(f, "integer out of range for {ty}")
}
Error::Io(e) => write!(f, "{e}"),
Error::At { path, error } => write!(f, "{path}: {error}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Parse(e) => Some(e),
Error::Language(e) => Some(e),
Error::Io(e) => Some(e),
Error::At { error, .. } => Some(&**error),
_ => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Io(e)
}
}
impl Error {
pub fn path(&self) -> Option<&str> {
match self {
Error::At { path, .. } => Some(path),
_ => None,
}
}
pub fn innermost(&self) -> &Error {
match self {
Error::At { error, .. } => error,
other => other,
}
}
#[doc(hidden)]
#[cold]
pub fn at_key(self, key: &str) -> Self {
self.prefixed(key)
}
#[doc(hidden)]
#[cold]
pub fn at_index(self, index: usize) -> Self {
self.prefixed(&format!("[{index}]"))
}
fn prefixed(self, segment: &str) -> Self {
match self {
Error::At { path, error } => {
let sep = if path.starts_with('[') { "" } else { "." };
Error::At {
path: format!("{segment}{sep}{path}"),
error,
}
}
e @ (Error::Parse(_) | Error::Io(_) | Error::Language(_)) => e,
other => Error::At {
path: segment.to_string(),
error: Box::new(other),
},
}
}
}
#[cfg(feature = "serde")]
impl serde::de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}
#[cfg(feature = "serde")]
impl serde::ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Error::Message(msg.to_string())
}
}