mirror of
https://github.com/MorizzG/rlox.git
synced 2025-12-06 04:12:42 +00:00
Chapter 7 done
This commit is contained in:
parent
42dbe531ad
commit
f56fcc4a8b
6 changed files with 186 additions and 19 deletions
58
src/error.rs
58
src/error.rs
|
|
@ -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 }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue