create ErrorMessage trait

This commit is contained in:
Josh Thomas 2024-10-14 14:59:04 -05:00
parent c0cd3ba89e
commit 0988c53008

View file

@ -1,40 +1,63 @@
use std::fmt;
pub trait ErrorMessage {
fn message(&self) -> &str;
}
#[derive(Debug)]
pub enum LexerError {
EmptyToken(usize),
UnexpectedCharacter(char, usize),
LexicalError { message: String, position: usize },
EmptyToken {
line: usize,
message: String,
},
UnexpectedCharacter {
character: char,
line: usize,
message: String,
},
LexicalError {
position: usize,
message: String,
},
}
impl LexerError {
pub fn empty_token<T>(line: usize) -> Result<T, Self> {
Err(LexerError::EmptyToken(line))
Err(LexerError::EmptyToken {
line,
message: format!("Empty token at line {}", line),
})
}
pub fn unexpected_character<T>(character: char, line: usize) -> Result<T, Self> {
Err(LexerError::UnexpectedCharacter(character, line))
Err(LexerError::UnexpectedCharacter {
character,
line,
message: format!("Unexpected character '{}' at line {}", character, line),
})
}
pub fn lexical_error<T>(message: &str, position: usize) -> Result<T, Self> {
Err(LexerError::LexicalError {
message: message.to_string(),
position,
message: format!("Lexical error at position {}: {}", position, message),
})
}
}
impl ErrorMessage for LexerError {
fn message(&self) -> &str {
match self {
LexerError::EmptyToken { message, .. }
| LexerError::UnexpectedCharacter { message, .. }
| LexerError::LexicalError { message, .. } => message,
}
}
}
impl fmt::Display for LexerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LexerError::EmptyToken(line) => write!(f, "Empty token at line {}", line),
LexerError::UnexpectedCharacter(c, line) => {
write!(f, "Unexpected character '{}' at line {}", c, line)
}
LexerError::LexicalError { message, position } => {
write!(f, "Lexical error at position {}: {}", position, message)
}
}
write!(f, "{}", self.message())
}
}