use std::{fmt, sync::Arc};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
pub(crate) kind: ErrorKind,
pub(crate) index: Index,
pub(crate) brainfuck: Arc<String>,
pub(crate) output: Option<String>,
}
impl Error {
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub fn line(&self) -> usize {
self.index.line
}
pub fn col(&self) -> usize {
self.index.col
}
pub fn brainfuck(&self) -> &str {
&self.brainfuck
}
pub fn brainfrick(&self) -> &str {
self.brainfuck()
}
pub fn output(&self) -> Option<&str> {
self.output.as_deref()
}
}
impl std::error::Error for Error {}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Index { line, col } = self.index;
writeln!(f, "{} @ line {} col {}", self.kind, line + 1, col + 1)?;
let line = self.brainfuck.lines().nth(line).expect("Invalid line");
let (start, dots_begin, mut offset) = match col.checked_sub(10) {
Some(num) => (num, num != 0, 11),
None => (0, false, col + 1),
};
let mut end = col + 10;
let dots_end = end < line.len();
if !dots_end {
end = line.len();
}
if dots_begin {
f.write_str("...")?;
offset += 3;
}
f.write_str(&line[start..end])?;
if dots_end {
f.write_str("...")?;
}
write!(f, "\n{0:>1$}", "^", offset)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
UnmatchedBracket,
MaxSteps,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Self::UnmatchedBracket => "Unmatched bracket",
Self::MaxSteps => "Max steps reached",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Index {
pub line: usize,
pub col: usize,
}
impl Index {
pub fn new(line: usize, col: usize) -> Self {
Self { line, col }
}
}