Chapter 7 done

This commit is contained in:
Moritz Gmeiner 2023-01-20 21:44:27 +01:00
commit f56fcc4a8b
6 changed files with 186 additions and 19 deletions

View file

@ -1,7 +1,9 @@
use thiserror::Error;
use crate::interpreter::Primitive;
use crate::lexer::Token;
use crate::misc::CodePos;
use crate::parser::expr::{BinaryOp, UnaryOp};
#[derive(Error, Debug)]
pub enum LexerError {
@ -27,31 +29,55 @@ pub enum ParserError {
UnexpectedToken { token: Token },
}
#[derive(Error, Debug)]
pub enum EvalError {
#[error("Unary operator {op} had invalid argument {arg}")]
UnaryOpInvalidArgument { op: UnaryOp, arg: Primitive },
#[error("Binary operator {op} had invalid arguments {left} and {right}")]
BinaryOpInvalidArguments {
left: Primitive,
op: BinaryOp,
right: Primitive,
},
#[error("Division by zero")]
DivisionByZero,
}
#[derive(Error, Debug)]
pub enum LoxError {
#[error("{msg}")]
LexerError { msg: String },
#[error("{msg}")]
ParserError { msg: String },
#[error("{0}", format_lexer_errors(inner))]
LexerError { inner: Vec<LexerError> },
#[error("{inner}")]
ParserError { inner: ParserError },
#[error("{inner}")]
EvalError { inner: EvalError },
}
fn format_lexer_errors(lexer_errs: &Vec<LexerError>) -> String {
let msg = if lexer_errs.len() == 1 {
format!("{}", lexer_errs[0])
} else {
let msgs: Vec<String> = lexer_errs.iter().map(|err| format!("{}", err)).collect();
msgs.join("\n")
};
msg
}
impl From<Vec<LexerError>> for LoxError {
fn from(lexer_errs: Vec<LexerError>) -> Self {
let msg = if lexer_errs.len() == 1 {
format!("{}", lexer_errs[0])
} else {
let msgs: Vec<String> = lexer_errs.iter().map(|err| format!("{}", err)).collect();
msgs.join("\n")
};
LoxError::LexerError { msg }
LoxError::LexerError { inner: lexer_errs }
}
}
impl From<ParserError> for LoxError {
fn from(parser_error: ParserError) -> Self {
LoxError::ParserError {
msg: format!("{parser_error}"),
}
fn from(parser_err: ParserError) -> Self {
LoxError::ParserError { inner: parser_err }
}
}
impl From<EvalError> for LoxError {
fn from(eval_err: EvalError) -> Self {
LoxError::EvalError { inner: eval_err }
}
}