use std::error::Error as StdError;
use std::fmt;
use crate::span::{Location, Span};
const MAX_PATH_BYTES: usize = 1024;
const MAX_KEY_CHARS: usize = 64;
const ELIDED: &str = "…";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidEncoding,
Scanner,
Parser,
Alias,
DuplicateKey,
Tag,
Resolution,
Limit,
Composition,
Serde,
Emitter,
Io,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = match self {
Self::InvalidEncoding => "invalid encoding",
Self::Scanner => "scanner error",
Self::Parser => "parser error",
Self::Alias => "alias error",
Self::DuplicateKey => "duplicate key",
Self::Tag => "tag error",
Self::Resolution => "scalar resolution error",
Self::Limit => "resource limit",
Self::Composition => "composition error",
Self::Serde => "serde error",
Self::Emitter => "emitter error",
Self::Io => "I/O error",
};
formatter.write_str(name)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Code {
#[default]
Unspecified,
ReservedIndicatorAfterBom,
UnexpectedMappingValue,
TrailingDocuments,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
code: Code,
path_len: u16,
context_len: u16,
span: Option<Span>,
message: String,
limit: Option<Box<crate::limits::LimitExceeded>>,
source: Option<Box<dyn StdError + Send + Sync + 'static>>,
}
impl Error {
#[must_use]
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
code: Code::Unspecified,
path_len: 0,
context_len: 0,
span: None,
message: message.into(),
limit: None,
source: None,
}
}
#[must_use]
pub(crate) fn with_code(mut self, code: Code) -> Self {
self.code = code;
self
}
#[cfg(feature = "libyaml-compat")]
#[must_use]
pub(crate) fn code(&self) -> Code {
self.code
}
#[must_use]
pub fn with_span(mut self, span: Span) -> Self {
self.span = Some(span);
self
}
#[cold]
pub(crate) fn with_context(mut self, context: &str) -> Self {
self.message.push_str(context);
self.context_len = u16::try_from(context.len()).unwrap_or(0);
self
}
#[must_use]
pub fn with_source(mut self, source: impl StdError + Send + Sync + 'static) -> Self {
self.source = Some(Box::new(source));
self
}
#[must_use]
pub fn with_limit(mut self, limit: crate::limits::LimitExceeded) -> Self {
self.limit = Some(Box::new(limit));
self
}
#[must_use]
pub fn limit(&self) -> Option<crate::limits::LimitExceeded> {
self.limit.as_deref().copied()
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub const fn span(&self) -> Option<Span> {
self.span
}
#[must_use]
pub fn location(&self) -> Option<Location> {
self.span.map(|span| span.start().location())
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[cold]
pub(crate) fn inside_index(self, index: usize) -> Self {
self.inside(&format!("[{index}]"))
}
#[cold]
pub(crate) fn inside_key(self, key: &str) -> Self {
if is_short_name(key) {
self.inside(key)
} else {
self.inside("ed_key(key))
}
}
#[cold]
pub(crate) fn inside_collection_key(self) -> Self {
self.inside("[?]")
}
fn inside(mut self, step: &str) -> Self {
let path_len = self.path_len as usize;
if path_len == 0 {
self.message.insert_str(0, ": ");
self.message.insert_str(0, step);
self.path_len = path_bytes(step.len() + 2);
return self;
}
if self.message.starts_with(ELIDED) {
return self;
}
let separator = if self.message.starts_with('[') {
""
} else {
"."
};
let step = if path_len + step.len() + separator.len() > MAX_PATH_BYTES {
ELIDED
} else {
step
};
self.message.insert_str(0, separator);
self.message.insert_str(0, step);
self.path_len = path_bytes(path_len + step.len() + separator.len());
self
}
}
fn path_bytes(len: usize) -> u16 {
u16::try_from(len).unwrap_or(u16::MAX)
}
fn is_short_name(key: &str) -> bool {
let mut chars = key.chars();
key.len() <= MAX_KEY_CHARS
&& chars
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
&& chars.all(|next| next.is_ascii_alphanumeric() || next == '_' || next == '-')
}
#[allow(
clippy::format_push_string,
reason = "one small escaped code point appended to an already-owned string"
)]
fn quoted_key(key: &str) -> String {
let mut quoted = String::from("[\"");
let mut chars = key.chars();
for next in chars.by_ref().take(MAX_KEY_CHARS) {
match next {
'"' | '\\' => {
quoted.push('\\');
quoted.push(next);
}
_ if hides_text(next) => {
quoted.push_str(&format!("\\u{{{:x}}}", u32::from(next)));
}
_ => quoted.push(next),
}
}
if chars.next().is_some() {
quoted.push_str(ELIDED);
}
quoted.push_str("\"]");
quoted
}
fn hides_text(character: char) -> bool {
character.is_control()
|| matches!(
character,
'\u{61c}'
| '\u{200e}'
| '\u{200f}'
| '\u{2028}'
| '\u{2029}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
| '\u{feff}'
)
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let Some(span) = self.span else {
return formatter.write_str(&self.message);
};
let (problem, context) = self
.message
.split_at(self.message.len() - self.context_len as usize);
let location = span.start().location();
write!(
formatter,
"{problem} at line {} column {}{context}",
location.line(),
location.column()
)
}
}
impl StdError for Error {
#[allow(
trivial_casts,
reason = "Box<dyn Error + Send + Sync> is widened to the plain error trait object"
)]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.source
.as_deref()
.map(|source| source as &(dyn StdError + 'static))
}
}
impl serde::de::Error for Error {
fn custom<T: fmt::Display>(message: T) -> Self {
Self::new(ErrorKind::Serde, message.to_string())
}
}
impl serde::ser::Error for Error {
fn custom<T: fmt::Display>(message: T) -> Self {
Self::new(ErrorKind::Serde, message.to_string())
}
}
#[cfg(test)]
mod tests {
use super::{Error, ErrorKind};
use crate::span::{Marker, Span};
use std::error::Error as _;
#[test]
fn kind_and_message_are_exposed() {
let error = Error::new(ErrorKind::Parser, "unexpected token");
assert_eq!(error.kind(), ErrorKind::Parser);
assert_eq!(error.message(), "unexpected token");
assert_eq!(error.to_string(), "unexpected token");
assert!(error.span().is_none());
assert!(error.location().is_none());
}
#[test]
fn span_and_location_are_one_based() {
let span = Span::new(Marker::new(4, 2, 3), Marker::new(5, 2, 4));
let error = Error::new(ErrorKind::Scanner, "bad token").with_span(span);
assert_eq!(error.span(), Some(span));
let location = error.location().expect("location");
assert_eq!((location.line(), location.column()), (2, 3));
}
#[test]
fn source_is_chained() {
let inner = std::io::Error::other("inner");
let error = Error::new(ErrorKind::Io, "outer").with_source(inner);
assert!(error.source().is_some());
}
#[test]
fn a_path_joins_its_steps_and_stands_before_the_message() {
let error = Error::new(ErrorKind::Serde, "bad")
.inside_key("c")
.inside_index(2)
.inside_key("b")
.inside_key("a b")
.inside_index(0);
assert_eq!(error.message(), "[0][\"a b\"].b[2].c: bad");
assert_eq!(error.kind(), ErrorKind::Serde);
let error = Error::new(ErrorKind::Serde, "bad").inside_collection_key();
assert_eq!(error.message(), "[?]: bad");
}
#[test]
fn a_key_is_bare_only_if_it_is_a_short_name() {
for bare in ["a", "_a", "runs-on", "a_1", &"k".repeat(64)] {
let error = Error::new(ErrorKind::Serde, "bad").inside_key(bare);
assert_eq!(error.message(), format!("{bare}: bad"));
}
for (key, shown) in [
("", "[\"\"]"),
("80", "[\"80\"]"),
("-a", "[\"-a\"]"),
("a.b", "[\"a.b\"]"),
("名前", "[\"名前\"]"),
("a\"b\\c", "[\"a\\\"b\\\\c\"]"),
("a\nb\u{1b}", "[\"a\\u{a}b\\u{1b}\"]"),
("\u{85}\u{2028}\u{2029}", "[\"\\u{85}\\u{2028}\\u{2029}\"]"),
("\u{200e}\u{200f}", "[\"\\u{200e}\\u{200f}\"]"),
("a\u{61c}b", "[\"a\\u{61c}b\"]"),
(
"\u{202e}\u{2066}\u{feff}",
"[\"\\u{202e}\\u{2066}\\u{feff}\"]",
),
] {
let error = Error::new(ErrorKind::Serde, "bad").inside_key(key);
assert_eq!(error.message(), format!("{shown}: bad"));
}
}
#[test]
fn a_long_key_and_a_long_path_are_cut_short() {
let error = Error::new(ErrorKind::Serde, "bad").inside_key(&"é".repeat(65));
assert_eq!(error.message(), format!("[\"{}…\"]: bad", "é".repeat(64)));
let mut error = Error::new(ErrorKind::Serde, "bad");
let name = "k".repeat(64);
for _ in 0..100 {
error = error.inside_key(&name);
}
let (path, rest) = error.message().split_once(": ").expect("a path");
assert_eq!(rest, "bad");
assert!(path.starts_with("….k"), "{path}");
assert!(path.len() <= 1024 + 4, "{}", path.len());
let before = error.message().to_owned();
let error = error.inside_key("outer").inside_index(1);
assert_eq!(error.message(), before);
let mut error = Error::new(ErrorKind::Serde, "bad").inside_index(7);
for _ in 0..200 {
error = error.inside_index(1_234_567);
}
assert!(error.message().starts_with("…["), "{}", error.message());
}
#[test]
fn a_location_in_the_text_does_not_stand_for_the_error_s() {
let span = Span::new(Marker::new(4, 2, 3), Marker::new(5, 2, 4));
let error = Error::new(ErrorKind::Serde, "bad")
.with_span(span)
.inside_key("at line 9");
assert_eq!(error.to_string(), "[\"at line 9\"]: bad at line 2 column 3");
let error = Error::new(ErrorKind::Serde, "invalid type: string \"at line 9\"")
.with_span(span)
.inside_key("a");
assert_eq!(
error.to_string(),
"a: invalid type: string \"at line 9\" at line 2 column 3"
);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn an_error_stays_small() {
assert_eq!(size_of::<Error>(), 112);
assert_eq!(size_of::<Result<crate::Value, Error>>(), 112);
}
#[test]
fn a_long_path_or_context_keeps_its_text() {
let long = "k".repeat(70_000);
let error = Error::new(ErrorKind::Serde, "bad").inside_key(&long);
assert!(
error.message().ends_with("…\"]: bad"),
"{}",
error.message()
);
let error = (0..2_000).fold(Error::new(ErrorKind::Serde, "bad"), |error, index| {
error.inside_index(index)
});
let start: String = error.message().chars().take(40).collect();
assert!(error.message().starts_with('…'), "{start}");
assert!(error.message().len() < 2_048);
let span = Span::new(Marker::new(4, 2, 3), Marker::new(5, 2, 4));
let context = format!(", {}", "c".repeat(70_000));
let error = Error::new(ErrorKind::Parser, "bad")
.with_context(&context)
.with_span(span);
assert_eq!(
error.to_string(),
format!("bad{context} at line 2 column 3")
);
}
#[test]
fn the_location_goes_before_the_context() {
let span = Span::new(Marker::new(4, 2, 3), Marker::new(5, 2, 4));
let error = Error::new(ErrorKind::Parser, "unterminated flow sequence")
.with_context(", opened at line 1 column 1")
.with_span(span);
assert_eq!(
error.message(),
"unterminated flow sequence, opened at line 1 column 1"
);
assert_eq!(
error.to_string(),
"unterminated flow sequence at line 2 column 3, opened at line 1 column 1"
);
let error = error.inside_index(0).inside_key("k");
assert_eq!(
error.to_string(),
"k[0]: unterminated flow sequence at line 2 column 3, opened at line 1 column 1"
);
let error = Error::new(ErrorKind::Parser, "unterminated flow sequence")
.with_context(", opened at line 1 column 1");
assert_eq!(
error.to_string(),
"unterminated flow sequence, opened at line 1 column 1"
);
}
#[test]
fn categories_display_stably() {
assert_eq!(ErrorKind::DuplicateKey.to_string(), "duplicate key");
assert_eq!(ErrorKind::Limit.to_string(), "resource limit");
}
}