able-script/ablescript/src/error.rs

67 lines
2 KiB
Rust
Raw Normal View History

use crate::{brian::InterpretError, lexer::Token};
2022-04-12 07:16:34 -05:00
use std::{fmt::Display, io, ops::Range};
#[derive(Debug)]
pub struct Error {
pub kind: ErrorKind,
pub span: Range<usize>,
}
#[derive(Debug)]
pub enum ErrorKind {
UnexpectedEof,
UnexpectedToken(Token),
UnknownVariable(String),
MeloVariable(String),
TopLevelEnough,
MissingLhs,
2022-05-06 10:25:50 -05:00
Brian(InterpretError),
Io(io::Error),
}
impl Error {
pub fn new(kind: ErrorKind, span: Range<usize>) -> Self {
Self { kind, span }
}
/// Create an UnexpectedEof error, where the EOF occurs at the
/// given index in the file.
pub fn unexpected_eof(index: usize) -> Self {
Self::new(ErrorKind::UnexpectedEof, index..index)
}
2021-04-27 06:48:56 -05:00
}
2021-07-13 13:54:27 -05:00
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Error at range {}-{}: {}",
self.span.start, self.span.end, self.kind
)
}
}
impl std::error::Error for Error {}
impl Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::UnexpectedEof => write!(f, "unexpected end of file"),
2021-12-29 17:06:46 -06:00
ErrorKind::UnexpectedToken(Token::Melo) => write!(f, "unexpected marten"),
2021-07-13 13:54:27 -05:00
ErrorKind::UnexpectedToken(token) => write!(f, "unexpected token {:?}", token),
ErrorKind::UnknownVariable(name) => write!(f, "unknown identifier \"{}\"", name),
ErrorKind::MeloVariable(name) => write!(f, "banned variable \"{}\"", name),
ErrorKind::TopLevelEnough => write!(f, "can only `enough` out of a loop"),
2022-05-06 10:25:50 -05:00
ErrorKind::Brian(err) => write!(f, "brainfuck error: {}", err),
2021-07-13 13:54:27 -05:00
// TODO: give concrete numbers here.
ErrorKind::MissingLhs => write!(f, "missing expression before binary operation"),
2022-05-06 10:25:50 -05:00
ErrorKind::Io(err) => write!(f, "I/O error: {}", err),
2021-07-13 13:54:27 -05:00
}
}
}
impl From<io::Error> for ErrorKind {
fn from(e: io::Error) -> Self {
2022-05-06 10:25:50 -05:00
Self::Io(e)
}
}