use crate::scalar::{line_end, line_start};
use std::fmt::{self, Display, Write};
pub struct Error {
inner: Box<Inner>,
}
struct Inner {
kind: ErrorKind,
message: String,
position: Option<Position>,
source: Option<std::io::Error>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Syntax,
Data,
Write,
Io,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LineColumn {
pub line: usize,
pub column: usize,
}
#[derive(Clone, Copy)]
struct Position {
line_column: LineColumn,
offset: usize,
}
impl Error {
#[cold]
fn unexpected(
kind: &str,
unexpected: serde_core::de::Unexpected<'_>,
expected: &dyn serde_core::de::Expected,
) -> Self {
if let serde_core::de::Unexpected::Str(text) = unexpected {
let text = crate::abbreviate(text, 40);
return Self::data(format!(
"invalid {kind}: {}, expected {expected}",
serde_core::de::Unexpected::Str(&text)
));
}
Self::data(format!("invalid {kind}: {unexpected}, expected {expected}"))
}
#[cold]
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
let mut message = message.into();
let sanitized = |character| {
if character == '\n' && kind != ErrorKind::Syntax {
character
} else {
sanitize(character)
}
};
if let Some((start, _)) = message
.char_indices()
.find(|&(_, character)| sanitized(character) != character)
{
let mut clean = String::with_capacity(message.len());
clean.push_str(&message[..start]);
clean.extend(message[start..].chars().map(sanitized));
message = clean;
}
Self {
inner: Box::new(Inner {
kind,
message,
position: None,
source: None,
}),
}
}
#[cold]
pub(crate) fn syntax(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Syntax, message)
}
#[cold]
pub(crate) fn data(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Data, message)
}
#[cold]
pub(crate) fn write(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Write, message)
}
#[cold]
pub(crate) fn io(error: std::io::Error) -> Self {
let mut io = Self::new(ErrorKind::Io, error.to_string());
io.inner.source = Some(error);
io
}
#[cold]
pub(crate) fn at(message: impl Into<String>, source: &str, offset: usize) -> Self {
let mut error = Self::syntax(message);
error.inner.position = Some(Position::locate(source, offset));
error
}
#[must_use]
pub fn with_position(message: impl Into<String>, text: &str, offset: usize) -> Self {
let mut error = Self::data(message);
error.inner.position = Some(Position::locate(text, offset));
error
}
#[cold]
pub(crate) fn or_at(mut self, source: Option<&str>, offset: Option<usize>) -> Self {
if self.inner.position.is_none()
&& let Some(source) = source
&& let Some(offset) = offset
{
self.inner.position = Some(Position::locate(source, offset));
}
self
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.inner.kind
}
#[must_use]
pub const fn message(&self) -> &str {
self.inner.message.as_str()
}
#[must_use]
pub const fn position(&self) -> Option<LineColumn> {
match self.inner.position {
Some(position) => Some(position.line_column),
None => None,
}
}
#[must_use]
pub const fn offset(&self) -> Option<usize> {
match self.inner.position {
Some(position) => Some(position.offset),
None => None,
}
}
#[must_use]
pub fn code_frame(&self, text: &str) -> Option<String> {
const CONTEXT_LINES: usize = 2;
let position = self.inner.position?;
let offset = character_start(text, position.offset);
let line = text.as_bytes()[..offset]
.iter()
.filter(|&&byte| byte == b'\n')
.count() + 1;
let mut starts = [0; CONTEXT_LINES + 1];
let mut first = CONTEXT_LINES;
starts[first] = line_start(text.as_bytes(), offset);
while first > 0 && starts[first] > 0 {
starts[first - 1] = line_start(text.as_bytes(), starts[first] - 1);
first -= 1;
}
let line_starts = &starts[first..];
let first_line = line + 1 - line_starts.len();
let gutter_width = line.ilog10() as usize + 1;
let mut frame = String::with_capacity(384);
for (index, &line_start) in line_starts.iter().enumerate() {
let number = first_line + index;
let is_error_line = number == line;
let line_end = line_end(text.as_bytes(), line_start);
let pointer = if is_error_line {
text[line_start..offset].chars().count()
} else {
0
};
let (characters, pointer) = clip(&text[line_start..line_end], pointer);
let marker = if is_error_line { '>' } else { ' ' };
if index > 0 {
frame.push('\n');
}
write!(frame, "{marker} {number:>gutter_width$} |")
.expect("writing to a String does not fail");
if !characters.is_empty() {
frame.push(' ');
frame.extend(characters.iter());
}
if is_error_line {
write!(frame, "\n {:gutter_width$} | ", "")
.expect("writing to a String does not fail");
frame.extend(
characters[..pointer]
.iter()
.map(|&character| if character == '\t' { '\t' } else { ' ' }),
);
frame.push('^');
}
}
Some(frame)
}
}
pub(crate) const fn sanitize(character: char) -> char {
let is_bidirectional_control = matches!(character, '\u{61C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}');
if (character.is_control() && character != '\t') || is_bidirectional_control {
'\u{FFFD}'
} else {
character
}
}
fn clip(line: &str, pointer: usize) -> (Vec<char>, usize) {
const MAX_LINE_WIDTH: usize = 100;
let length = line.chars().count();
if length <= MAX_LINE_WIDTH {
return (line.chars().map(sanitize).collect(), pointer);
}
let start = pointer
.saturating_sub(MAX_LINE_WIDTH / 2)
.min(length - MAX_LINE_WIDTH);
let end = start + MAX_LINE_WIDTH;
let mut clipped = Vec::with_capacity(MAX_LINE_WIDTH + 2);
if start > 0 {
clipped.push('…');
}
clipped.extend(line.chars().skip(start).take(MAX_LINE_WIDTH).map(sanitize));
if end < length {
clipped.push('…');
}
let pointer = pointer - start + usize::from(start > 0);
(clipped, pointer)
}
impl Position {
fn locate(source: &str, offset: usize) -> Self {
let offset = character_start(source, offset);
Self {
line_column: LineColumn::locate(source, offset),
offset,
}
}
}
fn character_start(text: &str, offset: usize) -> usize {
text.floor_char_boundary(offset)
}
impl LineColumn {
pub(crate) fn locate(source: &str, offset: usize) -> Self {
let offset = character_start(source, offset);
let before = &source.as_bytes()[..offset];
let line_start = line_start(source.as_bytes(), offset);
let line = before.iter().filter(|&&byte| byte == b'\n').count() + 1;
let column = before[line_start..]
.iter()
.filter(|&&byte| byte & 0xC0 != 0x80)
.count() + 1;
Self { line, column }
}
}
impl Display for LineColumn {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "line {}, column {}", self.line, self.column)
}
}
impl Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.inner.position {
Some(position) => write!(
formatter,
"{} at {}",
self.inner.message, position.line_column
),
None => formatter.write_str(&self.inner.message),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = formatter.debug_struct("Error");
debug.field("kind", &self.inner.kind);
debug.field("message", &self.inner.message);
if let Some(position) = self.inner.position {
debug.field("line", &position.line_column.line);
debug.field("column", &position.line_column.column);
}
debug.finish()
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner
.source
.as_ref()
.map(|error| error as &(dyn std::error::Error + 'static))
}
}
impl serde_core::de::Error for Error {
#[cold]
fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self {
let field = crate::abbreviate(field, 40);
let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_field(
&field, expected,
);
Self::data(error.to_string())
}
#[cold]
fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self {
let variant = crate::abbreviate(variant, 40);
let error = <serde_core::de::value::Error as serde_core::de::Error>::unknown_variant(
&variant, expected,
);
Self::data(error.to_string())
}
#[cold]
fn custom<T: Display>(message: T) -> Self {
Self::data(message.to_string())
}
#[cold]
fn invalid_type(
unexpected: serde_core::de::Unexpected<'_>,
expected: &dyn serde_core::de::Expected,
) -> Self {
Self::unexpected("type", unexpected, expected)
}
#[cold]
fn invalid_value(
unexpected: serde_core::de::Unexpected<'_>,
expected: &dyn serde_core::de::Expected,
) -> Self {
Self::unexpected("value", unexpected, expected)
}
}
impl serde_core::ser::Error for Error {
#[cold]
fn custom<T: Display>(message: T) -> Self {
Self::write(message.to_string())
}
}